Skip to content

Instantly share code, notes, and snippets.

@bleis-tift
Created May 10, 2012 07:08
Show Gist options
  • Save bleis-tift/2651599 to your computer and use it in GitHub Desktop.
Save bleis-tift/2651599 to your computer and use it in GitHub Desktop.
Active Pattern, Extractor, View Pattern
// F#
type Hoge = A of int | B of int | C of int
let (|AllHoge|) (A x | B x | C x) = AllHoge x
let f (AllHoge x) = x * 10
let xs = [A 1; B 2; C 3] |> List.map f
// Scala
sealed trait Hoge
case class A(v: Int) extends Hoge
case class B(v: Int) extends Hoge
case class C(v: Int) extends Hoge
object AllHoge {
def unapply(h: Hoge) =
h match {
case A(x) => Some(x)
case B(x) => Some(x)
case C(x) => Some(x)
}
}
val f: Hoge => Int = { case AllHoge(x) => x * 10 }
val xs = List(A(1), B(2), C(3)).map(f)
-- Haskell
data Hoge = A Integer | B Integer | C Integer deriving (Show)
allHoge :: Hoge -> Integer
allHoge (A n) = n
allHoge (B n) = n
allHoge (C n) = n
f :: Hoge -> Integer
f (allHoge -> n) = n * 10
xs = map f [A 1, B 2, C 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment