Skip to content

Instantly share code, notes, and snippets.

@jakobrs
Last active November 25, 2019 13:52
Show Gist options
  • Save jakobrs/08fbad0d5bf6297371a82a7de93d8732 to your computer and use it in GitHub Desktop.
Save jakobrs/08fbad0d5bf6297371a82a7de93d8732 to your computer and use it in GitHub Desktop.
Scott encoding ... again
data Expr = Var Int | Application Expr Expr | Abstraction Int Expr deriving (Show, Eq, Ord)
zeroExpr :: Expr
zeroExpr = Abstraction 0 (Abstraction 1 (Var 0))
succExpr :: Expr -> Expr
succExpr num = Abstraction 0 (Abstraction 1 (Application (Var 1) num))
isScottNum :: Expr -> Bool
isScottNum (Abstraction a (Abstraction b (Var c))) | a == c && a /= b = True -- Zero
isScottNum (Abstraction a (Abstraction b (Application (Var c) d))) | b == c = isScottNum d -- Succ
isScottNum _ = False -- otherwise
decodeScottNum :: Expr -> Maybe Int
decodeScottNum (Abstraction a (Abstraction b (Var c))) | a == c && a /= b = Just 0 -- Zero
decodeScottNum (Abstraction a (Abstraction b (Application (Var c) d))) | b == c = (+1) <$> decodeScottNum d -- Succ
decodeScottNum _ = Nothing -- otherwise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment