juan_gandhi: (VP)
2015-01-27 04:40 pm

on the verge of introducing Y-combinator

isAncestor = function(ancestor) {
  var check = function(descendant) {
    var p = descendant && descendant.parentNode
    return ancestor === p || !!(p && check(p))
  };
  return check
}
juan_gandhi: (Default)
2010-08-30 08:29 pm
Entry tags:

visitor pattern, scala sample


scala> abstract class N[T]                                                                                                                  
defined class N

scala> case class L[T](v:T) extends N[T]                                                                                 
defined class L

scala> case class B[T](kids:List[N[T]]) extends N[T]                                                                     
defined class B

scala> val t = B(List(B(List(L("ab"),L("cd"),B(List(L("xy"),L("z"))))),L("middle")))                                                        
t: B[java.lang.String] = B(List(B(List(L(ab), L(cd), B(List(L(xy), L(z))))), L(middle)))

scala> def scan[T](tree:N[T]):List[T] = tree match { case L(v) => List(v); case B(kids) => kids flatMap (scan(_)) } 
scan: [T](N[T])List[T]

scala> scan(t)                                                                                                                 
res17: List[java.lang.String] = List(ab, cd, xy, z, middle)

scala> 


I used repl, so it's kind of too laconic; in real life you probaly won't call your class N, L and B. But you know what I mean, right?