Advertisement
HXXXXJ

Binary expression tree - pass in closure

Apr 12th, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.68 KB | None | 0 0
  1.  
  2. indirect enum CalcNode <T>{
  3.     typealias fuction = (T, T) -> T
  4.     case node(CalcNode <T>, CalcNode <T>, fuction)
  5.     case leaf(T)
  6.     func MyValue() -> T{
  7.         switch self {
  8.         case let .node(left, right, function):
  9.             let leftR = left.MyValue()
  10.             let rightR = right.MyValue()
  11.             return function(leftR, rightR)
  12.         case let .leaf(value):
  13.             return value
  14.         }
  15.     }
  16. }
  17.  
  18. let add = { ( a1, a2) -> Int in
  19.     return a1 + a2
  20. }
  21.  
  22. let minus = { ( a1, a2) -> Int in
  23.     return a1 - a2
  24. }
  25.  
  26.  
  27. let node1 = CalcNode.leaf(3)
  28. let node2 = CalcNode.leaf(4)
  29. let node3 = CalcNode.node(node1, node2, add)
  30.  
  31. print(node3.MyValue())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement