Skip to content

Instantly share code, notes, and snippets.

@TheSeamau5
Created April 12, 2015 14:59
Show Gist options
  • Save TheSeamau5/9f2f8d0fde0a3d631042 to your computer and use it in GitHub Desktop.
Save TheSeamau5/9f2f8d0fde0a3d631042 to your computer and use it in GitHub Desktop.
String Match On
matchOn : String -> String -> Maybe String
matchOn start string =
if startsWith start string
then
Just <| dropLeft (length start) string
else
Nothing
@TheSeamau5
Copy link
Author

Can be used for easy routing:

match : String -> String
match url = case url of
  "index.html" -> "Home Page"
  ""           -> "Home Page"
  _            -> 
    case matchOn "blog/" url of
      Just value -> "Some blog : " ++ value
      Nothing    -> 
    case matchOn "contacts/" url of
      Just value -> "Some contacts : " ++ value
      Nothing -> "404"

@TheSeamau5
Copy link
Author

With a DSL too:

(:->) = (,)       

route = match 
  [ "index.html" :-> displayHome
  , ""           :-> displayHome
  , "blog/"      :-> blogRoute
  , "contacts/"  :-> displayContacts
  ] display404


blogRoute = match
  [ "mario.html" :-> displayMario
  ] displayBlog

@TheSeamau5
Copy link
Author

The match function for the DSL:

match : List (String, String -> a) -> (String -> a) -> String -> a
match list defaultMatch url = case list of
  [] -> defaultMatch url
  (str, matcher) :: ms -> 
    -- Test for empty string matcher (usually home)
    if 
      str == "" 
    then
      if 
        url == ""
      then 
        matcher url
      else
        match ms defaultMatch url
    else 
      case matchOn str url of
        Just value -> matcher value
        Nothing    -> match ms defaultMatch url

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment