Vandexel Vandexel - 2 months ago 7
Scala Question

How do I call this maptree function in Scala?

I am rather new to Scala and I have been given this function

def map_tree[A,B](f: A => B)(tree: Tree[A]): Tree[B] =
tree match {
case Leaf(value) => Leaf(f (value))
case Node(value , l, r) => Node(f (value), map_tree (f) (l), map_tree (f) (r))
}


Here is my Tree class and Leaf and Node definitions

abstract class Tree[+A]
case class Leaf[A](value: A) extends Tree[A]
case class Node[A](value: A, left: Tree[A], right: Tree[A]) extends Tree[A]


How would I call this map_tree function within another function?

For example if I had this function

def add_n(t: Tree[Int], n: Int) : Tree[Int] =


How can I call map_tree in it to cause it to add n to every element in the tree?

def add_n(t: Tree[Int], n: Int) : Tree[Int] =
map_tree(what do I input here)?


I have tried calling it like this:

map_tree( t => t+n)(t)


But it is telling me "Invalid parameter type". I think that is not what the input should be, but I'm not sure what I am supposed enter in the first parentheses in map_tree

Answer

I get a different error message (in Scala 2.11.8):

scala> abstract class Tree[+A]
defined class Tree

scala>   case class Leaf[A](value: A) extends Tree[A]
defined class Leaf

scala>   case class Node[A](value: A, left: Tree[A], right: Tree[A]) extends Tree[A]
defined class Node

scala> def map_tree[A,B](f: A => B)(tree: Tree[A]): Tree[B] =
     |   tree match {
     |     case Leaf(value) => Leaf(f (value))
     |     case Node(value , l, r) => Node(f (value), map_tree (f) (l), map_tree (f) (r))
     | }
map_tree: [A, B](f: A => B)(tree: Tree[A])Tree[B]

scala> def add_n(t: Tree[Int], n: Int) : Tree[Int] = map_tree( t => t+n)(t)
<console>:17: error: missing parameter type
       def add_n(t: Tree[Int], n: Int) : Tree[Int] = map_tree( t => t+n)(t)

Anyway, this is just type inference failing you, as happens sometimes. It works fine if you give it the type args explicitly:

scala> def add_n(t: Tree[Int], n: Int): Tree[Int] = map_tree[Int, Int](t => t + n)(t)
add_n: (t: Tree[Int], n: Int)Tree[Int]
Comments