1 object OnOffDevice { 2 import Appliance.onOffDevice 3 def on: Reader[Appliance,String] = onOffDevice map { _.on } 4 def off: Reader[Appliance,String] = onOffDevice map { _.off } 5 } 6 object SensorDevice { 7 import Appliance.sensorDevice 8 def isCoffeePresent: Reader[Appliance,Boolean] = sensorDevice map { _.isCoffeePresent } 9 } 10 object PowerConfig { 11 import Appliance.powerConfig 12 def getPowerVolts(country: String) = powerConfig map {_.getPowerVolts(country)} 13 def isUSStandard(volts: Int) = powerConfig map {_.isUSStandard(volts)} 14 }
1 object OnOffService { 2 def on = for { 3 ison <- OnOffDevice.on 4 } yield ison 5 def off = for { 6 isoff <- OnOffDevice.off 7 } yield isoff 8 } 9 object SensorService { 10 def isCoffeePresent = for { 11 hasCoffee <- SensorDevice.isCoffeePresent 12 } yield hasCoffee 13 } 14 object PowerService { 15 def isUSStandard(country: String) = for { 16 is110v <- PowerConfig.getPowerVolts(country) 17 isUSS <- PowerConfig.isUSStandard(is110v) 18 } yield isUSS 19 }
1 class OnOffDeviceImpl extends OnOffDevice { 2 def on = "SomeDevice.On"
3 def off = "SomeDevice.Off"
4 } 5 class SensorDeviceImpl extends SensorDevice { 6 def isCoffeePresent = true
7 } 8 class PowerConfigImpl extends PowerConfig { 9 def getPowerVolts(country: String) = country match { 10 case "USA" => 110
11 case "UK" => 220
12 case "HK" => 220
13 case "CHN" => 110
14 case _ => 0
15 } 16 def isUSStandard(volts: Int) = volts === 110
17 }
1 object MockOnOffDevice extends OnOffDeviceImpl 2 object MockSensorDevice extends SensorDeviceImpl 3 object MockPowerConfig extends PowerConfigImpl 4 trait OnOffFunctions extends OnOffComponent { 5 def onOffDevice = MockOnOffDevice 6 } 7 trait SensorFunctions extends SensorComponent { 8 def sensorDevice = MockSensorDevice 9 } 10 trait DeviceFunctions extends DeviceComponent { 11 def onOffDevice = MockOnOffDevice 12 def sensorDevice = MockSensorDevice 13 } 14 trait PowerFunctions extends PowerComponent { 15 def powerConfig = MockPowerConfig 16 }
1 object MockAppliance extends Appliance with DeviceFunctions with PowerFunctions
1 def trigger =
2 if ((PowerService.isUSStandard("CHN")(MockAppliance)) 3 && (SensorService.isCoffeePresent(MockAppliance))) 4 OnOffService.on(MockAppliance) 5 else
6 OnOffService.off(MockAppliance) //> trigger: => scalaz.Id.Id[String]
7 trigger //> res0: scalaz.Id.Id[String] = SomeDevice.On
1 package Exercises 2 import scalaz._ 3 import Scalaz._ 4 object reader3 { 5 trait OnOffDevice { 6 def on: String 7 def off: String 8 } 9 trait SensorDevice { 10 def isCoffeePresent: Boolean 11 } 12 trait PowerConfig { 13 def getPowerVolts(country: String): Int 14 def isUSStandard(volt: Int): Boolean 15 } 16
17 trait OnOffComponent { 18 def onOffDevice: OnOffDevice 19 } 20 trait SensorComponent { 21 def sensorDevice: SensorDevice 22 } 23 trait Device extends OnOffComponent with SensorComponent 24 trait DeviceComponent { 25 def onOffDevice: OnOffDevice 26 def sensorDevice: SensorDevice 27 } 28 trait PowerComp