Skip to content

Instantly share code, notes, and snippets.

@NicolasT
Created September 8, 2015 22:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NicolasT/e8edde87a4f18dc082a9 to your computer and use it in GitHub Desktop.
Save NicolasT/e8edde87a4f18dc082a9 to your computer and use it in GitHub Desktop.
Haskell representation of F#-style Active Patterns
-- https://www.reddit.com/r/haskell/comments/3huexy/what_are_haskellers_critiques_of_f_and_ocaml/cuisrmj
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}
module Main where
import Text.Read (readMaybe)
pattern Even <- ((`mod` 2) -> 0)
pattern Odd <- ((`mod` 2) -> 1)
f :: Int -> String
f n = case n of
Even -> show n ++ " is even"
Odd -> show n ++ " is odd"
-- For totality: _ -> error "Impossible"
pattern IntLiteral :: Int -> String
pattern IntLiteral i <- (readMaybe -> Just i)
g :: String -> String
g n = case n of
IntLiteral i -> show i ++ " is a valid int literal"
_ -> n ++ " is an invalid int literal"
main :: IO ()
main = do
mapM_ (putStrLn . f) [0 .. 3]
putStrLn $ g "123"
putStrLn $ g "abc"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment