Last active
December 16, 2015 22:29
-
-
Save tokiwoousaka/5507329 to your computer and use it in GitHub Desktop.
egisonではリストもmaybeも、matcherを適切に実装する事で、同じマッチ式でパターンマッチする事ができる。
This file contains 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
(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