charles-river-analytics / figaro

Figaro Programming Language and Core Libraries
Other
756 stars 151 forks source link

Question about the "Wrong side of bed" modification to Hello World. #755

Closed bjenkinsgit closed 2 years ago

bjenkinsgit commented 2 years ago

On page 55 in the section 2.8 in the Exercises, exercise 1 asks to extend Hello World program to add a variable to represent getting out on the wrong side of the bed. It says to modify the code such that “if you got out of the wrong side of the bed, the greeting is ALWAYS 'oh no, not again’. If you got out on the right side of the bed, the greeting logic is the same as before.” I have tried the following and would like to know why this approach does not work:

 val wrongSideOfBed = Flip(0.5)  // We have a 50/50 change of getting up from the wrong side of the bed.
  val sunnyToday = Flip(0.2)                    //#B
   val greetingToday = If (wrongSideOfBed,Select(1.0 -> "Uh oh, wrong side of bed.",
      If(sunnyToday,                //#C
       Select(0.6 -> "Hello, world!", 0.4 -> "Howdy, universe!"),   //#C
       Select(0.2 -> "Hello, world!", 0.8 -> "Oh no, not again"))
       ))   //#C

But the Scala compiler is complaining at the Select in the section If (wrongSideOfBed,Select Does anyone have a working solution to this exercise that I can study? Can we not arbitrarily nest Ifs and Selects like normal Scala code?

bjenkinsgit commented 2 years ago

Ok. I think I found a working solution. Changing the first two lines of the original code to the following seems to be what is needed:

  val correctSideOfBed = Flip(0.0)  // <-- 0.0 = wrong side of the bed, 1.0 right side, 0-1 = could be either?
  val sunnyToday = Chain(correctSideOfBed, (isCorrectRightSideOfBed: Boolean) => if (isCorrectRightSideOfBed) Flip(.2) else Flip(0.0)) //Flip(0.2)                  //#B