Skip to content

Instantly share code, notes, and snippets.

@co1rowjp
Created December 10, 2012 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save co1rowjp/4252025 to your computer and use it in GitHub Desktop.
Save co1rowjp/4252025 to your computer and use it in GitHub Desktop.
TypeScript Maybe(I want pattern match..)
interface Functor {
fmap: (any) => any;
}
interface Monad extends Functor {
bind: (any) => Monad;
}
interface MaybeMatcher {
just: (any) => Maybe;
nothing: () => Maybe;
}
interface Maybe extends Monad {
fmap: (any) => any;
bind: (any) => Maybe;
match: (MaybeMatcher) => Maybe;
}
class Just implements Maybe {
private value: any;
constructor(a: any) {
this.value = a
}
fmap (f: (any) => any): Just {
return new Just(f(this.value))
}
bind (f: (any) => Maybe): Maybe {
return f(this.value)
}
match (matcher: MaybeMatcher): Maybe {
return matcher.just(this.value)
}
}
class Nothing implements Maybe {
fmap (f: (any) => any): Nothing {
return this
}
bind (f: (any) => Maybe): Maybe {
return this
}
match (matcher: MaybeMatcher): Maybe {
return matcher.nothing()
}
}
var maybe = new Just("hoge")
var matched = maybe.match({
just: (s: any): Maybe => {
return new Just(s + "hoge")
},
nothing: (): Maybe => {
return new Just("nothing..")
}
})
matched.fmap((s: any): any => {console.log(s)})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment