Created
September 2, 2011 12:36
-
-
Save folone/1188506 to your computer and use it in GitHub Desktop.
Factorial with type magic. There's more here: http://www.willamette.edu/~fruehr/haskell/evolution.html
This file contains 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
-- static Peano constructors and numerals | |
data Zero | |
data Succ n | |
type One = Succ Zero | |
type Two = Succ One | |
type Three = Succ Two | |
type Four = Succ Three | |
-- dynamic representatives for static Peanos | |
zero = undefined :: Zero | |
one = undefined :: One | |
two = undefined :: Two | |
three = undefined :: Three | |
four = undefined :: Four | |
-- addition, a la Prolog | |
class Add a b c | a b -> c where | |
add :: a -> b -> c | |
instance Add Zero b b | |
instance Add a b c => Add (Succ a) b (Succ c) | |
-- multiplication, a la Prolog | |
class Mul a b c | a b -> c where | |
mul :: a -> b -> c | |
instance Mul Zero b Zero | |
instance (Mul a b c, Add b c d) => Mul (Succ a) b d | |
-- factorial, a la Prolog | |
class Fac a b | a -> b where | |
fac :: a -> b | |
instance Fac Zero One | |
instance (Fac n k, Mul (Succ n) k m) => Fac (Succ n) m | |
-- try, for "instance" (sorry): | |
-- | |
-- :t fac four |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment