Skip to content

Instantly share code, notes, and snippets.

@tokiwoousaka
Last active December 16, 2015 22:29
Show Gist options
  • Save tokiwoousaka/5507329 to your computer and use it in GitHub Desktop.
Save tokiwoousaka/5507329 to your computer and use it in GitHub Desktop.
egisonではリストもmaybeも、matcherを適切に実装する事で、同じマッチ式でパターンマッチする事ができる。
(define $maybe
(lambda [$a]
(matcher {
;; <primitive-pp>
[,$val [a] {[$tgt
(match [val tgt] [(maybe a) (maybe a)] {
[[<just $x> <just ,x>] {[x]}]
[[<nothing> <nothing>] {[]}]
[_ {}]})]}]
;; <primitive-dp>
[<just $> [a] {[<Just $x> {[x]}] [_ {}]}]
[<nothing> [] {[<Nothing> {[]}] [_ {}]}]})))
(define $maybe-list
(lambda [$a]
(matcher {
;; <primitive-pp>
[,$val [a] {[$tgt
(match [val tgt] [(maybe-list a) (maybe-list a)] {
[[<just $x> <just ,x>] {[x]}]
[[<nothing> <nothing>] {[]}]
[_ {}]})]}]
;; <primitive-dp>
[<just $ ,$xs> [a] {[{$x @$xs} {[x]}] [_ {}]}]
[<nothing> [] {[{} {[]}] [_ {}]}]})))
;;-----------------------------------------------------------------------
;; <Nothing>を<nothing>とパターンマッチ => <OK>
(test (match <Nothing> (maybe integer) {
[<nothing> <OK>]
[_ <KO>]}))
;;Nilを<nothing>とパターンマッチ => <OK>
(test (match {} (maybe-list integer) {
[<nothing> <OK>]
[_ <KO>]}))
;;-----------------------------------------------------------------------
;;<Just 999>を<just $x>とパターンマッチ => <OK 999>
(test (match <Just 999> (maybe integer) {
[<just $x> <OK x>]
[_ <KO>]}))
;;リスト{999 1 2}を<just $x>とパターンマッチ => <OK 999>
(test (match {999 1 2} (maybe-list integer) {
[<just $x> <OK x>]
[_ <KO>]}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment