Skip to content

Instantly share code, notes, and snippets.

@faustind
Created September 12, 2021 20:14
Show Gist options
  • Save faustind/fa14fe60b8995a54e2e09552a6279b15 to your computer and use it in GitHub Desktop.
Save faustind/fa14fe60b8995a54e2e09552a6279b15 to your computer and use it in GitHub Desktop.
Example of Haskell rewrite rules with case and let exprs
module LC where
import Data.Char (ord, chr)
{-# Rules
"f/case" forall x. foo2int x = case x of
Bar n -> n
Baz n c -> ord c;
#-}
{-# Rules
"int2foo/let1" forall n. int2foo n =
let x = n in
let c = chr x in
Baz x c ;
#-}
data Foo a b = Bar a | Baz a b
-- deriving (Show)
{-# NOINLINE foo2int #-}
foo2int :: Foo Int Char -> Int
foo2int x = 0
{-# NOINLINE int2foo #-}
int2foo :: Int -> Foo Int Char
int2foo = Bar
e = foo2int (Bar 99)
{-# NOINLINE kaze #-}
kaze :: Foo Int Char -> Int
kaze e = case e of
Bar n -> n
Baz n c -> ord c
{-# NOINLINE let1 #-}
let1 :: Foo Int Char
let1 = let x = 1 in Bar x
{-# NOINLINE let2 #-}
let2 :: Foo Int Char
let2 = let x = 1 in
let y = 'c' in Baz x y
@faustind
Copy link
Author

Compile to visualize the rules using

alias ghc-core="ghc -O -dsuppress-idinfo -fenable-rewrite-rules -ddump-rules \
-dsuppress-coercions -dsuppress-type-applications \
-dsuppress-uniques -dsuppress-module-prefixes"

as in

ghc-core let_case.hs

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