scala - Passing in An Operator as a Parameter -


i'm doing exercise in "scala impatient", chapter 14, q8:

essentially need create function (utilizing pattern matching) takes in operator , nodes, , outputs result of operation. e.g. node(+, node(*, leaf(2), leaf(3)) leaf(1)) should output 7.

here of given classes:

sealed abstract class binarytree case class leaf(value: int) extends binarytree 

so create node class, i'm having difficulties figuring out how pass in operator.

case class node(op: function (what goes here?) , leaves: binarytree*) extends binarytree 

i want use pattern matching so:

  tree match {     case node(op, leaves @ _*) => op match {       case op : function => leaves.reduceleft(_ op _)     }     case leaf: leaf => leaf.value 

but

case op : function => leaves.reduceleft(_ op _) 

part wrong. don't know how use operator that's being passed in node class. doing wrong here?

i assuming operator going binary hence, our called binarytree have atleast 2 operands :

  trait binarytree    case class leaf(value: int) extends binarytree    case class node(op: function2[int, int, int], l1: binarytree*) extends binarytree    object operators {     val + = (a: int, b: int) => + b     val * = (a: int, b: int) => * b   }    def f(tree: binarytree): int = {     tree match {       case n: node => n.l1.map(f).reduceleft((r,c) => n.op(r,c))       case leaf: leaf => leaf.value     }   } 

some test results:

simple one:

scala>   f(node(operators.*,leaf(4),leaf(2),leaf(3))) res4: int = 24  scala> f(node(operators.+,           node(operators.*, leaf(2), leaf(1), leaf(4), leaf(5)), leaf(6))) res5: int = 46  scala>   f(node(operators.+,            node(operators.*, leaf(2), leaf(1), leaf(4), leaf(5)),           node(operators.+,leaf(9),leaf(9)), leaf(6))) res6: int = 64 

quite complex:

scala> f(node(operators.+,           node(operators.*, leaf(2), leaf(1),            node(operators.* ,leaf(4), leaf(5) ,leaf(2))),           node(operators.+,leaf(9),leaf(9)), leaf(6),           node(operators.*, leaf(2), leaf(2)))) res7: int = 108 

Comments