Created
September 8, 2015 22:54
-
-
Save NicolasT/e8edde87a4f18dc082a9 to your computer and use it in GitHub Desktop.
Haskell representation of F#-style Active Patterns
This file contains hidden or 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
-- 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