Last active
August 29, 2015 14:07
-
-
Save piyo7/d9079f6382a6a17d3ea7 to your computer and use it in GitHub Desktop.
Scalaにおけるバリアント型の表現 ref: http://qiita.com/piyo7/items/e57cf08bbfd7557303d2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* Binary tree with leaves carrying an integer. *) | |
type tree = Leaf of int | Node of tree * tree | |
let rec exists_leaf test tree = | |
match tree with | |
| Leaf v -> test v | |
| Node (left, right) -> | |
exists_leaf test left | |
|| exists_leaf test right | |
let has_even_leaf tree = | |
exists_leaf (fun n -> n mod 2 = 0) tree |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sealed trait Tree[T] | |
case class Leaf[T](v: T) extends Tree[T] | |
case class Node[T](left: Tree[T], right: Tree[T]) extends Tree[T] | |
def exists_leaf[T](test: T => Boolean, tree: Tree[T]): Boolean = { | |
tree match { | |
case Leaf(v) => test(v) | |
case Node(left, right) => | |
exists_leaf(test, left) || | |
exists_leaf(test, right) | |
} | |
} | |
def has_even_leaf(tree: Tree[Int]): Boolean = | |
exists_leaf[Int](_ % 2 == 0, tree) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment