Programmation appliquée en Scala

Copyright © Cay S. Horstmann 2015 Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License

Laziness

By-Name Parameters

Let's define if/else

Which of these will work? We want to call

ifElse(i < 5, println("Hi"), println("Bye"))

  1. def ifElse(c: Boolean, a: Unit, b: Unit) {
      c && { a; true } || { b; true } }
  2. def ifElse(c: Boolean, a: => Unit, b: => Unit) {
      c && { a; true } || { b; true } }
  3. def ifElse(c: => Boolean, a: => Unit, b: => Unit) {
      c && { a; true } || { b; true } }
  4. None of these will work

lazy val

Lab

Scary looking lab

Part 1: Do-It-Yourself while

  1. You've seen how to implement an if/else statement in Scala. Now we want to do the same with while. We have two arguments, the condition and the body. For example,
    val iter = Source.fromFile("/usr/share/dict/words").getLines.buffered
      // "buffered" gives you an iterator with a "head" method for lookahead
    While(iter.head.length < 15, iter.next)
    val longWord = iter.head // The first word of length >= 15
    
    How do you declare While? (Just the header, not the implementation.)
  2. Now on with the implementation. If the condition is true, execute the body. Then call the function recursively. What do you get when running the code snippet above?
  3. It's a little ugly. Make it so that you can call
    While(iter.head.length < 15) { iter.next }
    Hint: Curry

Homework

Do this as individual work, not with your partner

When all done, email the signed zip files to Fatemeh.Borran@heig-vd.ch