Skip to content

Instantly share code, notes, and snippets.

@r-wheeler
Created March 17, 2015 14:53
Show Gist options
  • Select an option

  • Save r-wheeler/6de2f73df0c260a5ee1c to your computer and use it in GitHub Desktop.

Select an option

Save r-wheeler/6de2f73df0c260a5ee1c to your computer and use it in GitHub Desktop.
Daily Programmer 206
//http://www.reddit.com/r/dailyprogrammer/comments/2z68di/20150316_challenge_206_easy_recurrence_relations/
// skip the IO
val y = "*3 +2 *2"
def f(s: String, x: Int, n: Int): Unit = {
def rawF(s: String): Int => Int =
s(0) match {
case '+' => (x: Int) => x + s(1).toString.toInt
case '*' => (x: Int) => x * s(1).toString.toInt
case '/' => (x: Int) => x / s(1).toString.toInt
case '-' => (x: Int) => x - s(1).toString.toInt
}
//convert each string operation to a function
val funcs = s.split("\\s").map(rawF(_)).toList
//fold the list of functions, applying them recursivly to the input
Stream.from(x).map(v => funcs.foldLeft(v){case (acc,f) => f(acc)}).take(n).foreach(println)
}
f(y,1,8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment