summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKjetil Orbekk <kjetil.orbekk@gmail.com>2017-02-15 22:52:26 -0500
committerKjetil Orbekk <kjetil.orbekk@gmail.com>2017-02-15 22:52:26 -0500
commit0d55d50a30554e707f499b5814b54e8643d93354 (patch)
tree8c4388ed249fd157ab6b125e2f8ac5e4e10edb2c
parent89a9bba5a686f2ad03d7e5c9ece88de1cba72835 (diff)
Add dispatch stuff.
-rw-r--r--Dispatch.idr53
1 files changed, 53 insertions, 0 deletions
diff --git a/Dispatch.idr b/Dispatch.idr
new file mode 100644
index 0000000..a13fef4
--- /dev/null
+++ b/Dispatch.idr
@@ -0,0 +1,53 @@
+module Main
+
+%default total
+
+data Matcher =
+ Directory String Matcher
+ | Capture Matcher
+ | End
+
+HandlerType : Matcher -> Type
+HandlerType (Directory s m) = HandlerType m
+HandlerType (Capture m) = String -> HandlerType m
+HandlerType End = String
+
+Handler : Type
+Handler = (m : Matcher ** HandlerType m)
+
+dispatch : (handlers : List Handler) -> String -> Maybe String
+dispatch [] _ = Nothing
+dispatch handlers path = go handlers components where
+ components : List String
+ components = filter (/="") (split (=='/') path)
+
+ go : List Handler -> List String -> Maybe String
+ go [] cs = Nothing
+ go ((m ** f) :: hs) cs =
+ let next = go hs cs in
+ case m of
+ Directory dir matcher => case cs of
+ (c :: cs') => if c == dir then go ((matcher ** f) :: hs) cs' else next
+ _ => next
+ Capture matcher => case cs of
+ (c :: cs') => go ((matcher ** f c) :: hs) cs'
+ _ => next
+ End => Just f
+
+helloHandler : String -> String -> String
+helloHandler firstName lastName = "Hello, " ++ firstName ++ " " ++ lastName
+
+weatherHandler : String -> String
+weatherHandler place = "The weather in " ++ place ++ " is cold."
+
+handlers : List Handler
+handlers = [
+ (Directory "hello" (Capture (Capture End)) ** helloHandler)
+ , (Directory "weather" (Capture End) ** weatherHandler)
+ ]
+
+partial
+main : IO ()
+main = do
+ putStrLn (fromMaybe "failed" $ dispatch handlers "hello/Bob/Sunshine")
+ putStrLn (fromMaybe "failed" $ dispatch handlers "weather/New York")