Added a fun Maybe example!

This commit is contained in:
Samuel Hammersberg 2023-03-29 16:47:52 +02:00
parent d4115fd2f5
commit d26bde6a7f
2 changed files with 63 additions and 18 deletions

View file

@ -328,7 +328,7 @@ compileExp (MIR.EAdd e1 e2, t) = emitAdd t e1 e2
compileExp (MIR.EVar name, _t) = emitIdent name
compileExp (MIR.EApp e1 e2, t) = emitApp t e1 e2
-- compileExp (EAbs t ti e) = emitAbs t ti e
compileExp (MIR.ELet _binds _e, _t) = undefined -- emitLet binds (fst e)
compileExp (MIR.ELet bind e, _) = emitLet bind e
compileExp (MIR.ECase e cs, t) = emitECased t e (map (t,) cs)
-- go (EMul e1 e2) = emitMul e1 e2
@ -336,6 +336,17 @@ compileExp (MIR.ECase e cs, t) = emitECased t e (map (t,) cs)
-- go (EMod e1 e2) = emitMod e1 e2
--- aux functions ---
emitLet :: MIR.Bind -> ExpT -> CompilerState ()
emitLet (MIR.Bind id [] innerExp) e = do
evaled <- exprToValue innerExp
tempVar <- getNewVar
let t = type2LlvmType . snd $ innerExp
emit $ SetVariable tempVar (Alloca t)
emit $ Store (type2LlvmType . snd $ innerExp) evaled Ptr tempVar
emit $ SetVariable (fst id) (Load t Ptr tempVar)
compileExp e
emitLet b _ = error $ "Non empty argument list in let-bind " <> show b
emitECased :: MIR.Type -> ExpT -> [(MIR.Type, Branch)] -> CompilerState ()
emitECased t e cases = do
let cs = snd <$> cases

View file

@ -1,31 +1,51 @@
-- main = head (Cons (sum (repeat 10 5)) Nil);
main = case (bind (fmap (\s . s + 1) (Just 5)) (\s . pure (s + 10))) of {
Just a => a ;
Nothing => minusOne ;
};
---- MAYBE MONAD ----
data Maybe () where {
Just : Int -> Maybe ()
Nothing : Maybe ()
};
fmap : (Int -> Int) -> Maybe () -> Maybe () ;
fmap f m = case m of {
Just a => pure (f a) ;
Nothing => Nothing ;
};
pure : Int -> Maybe () ;
pure x = Just x;
-- scombinator not working yet :)
bind : Maybe () -> (Int -> Maybe ()) -> Maybe () ;
bind x f = case x of {
Just x => f x ;
Nothing => Nothing ;
};
-- represents minus one :)
minusOne : Int ;
minusOne = 9223372036854775807 + 9223372036854775807 + 1;
{-
---- LIST STUFF ----
-- a simple list data type containing ints
data List () where {
Cons : Int -> List () -> List ()
Nil : List ()
};
main = head (repeat 10 5);
head : List () -> Int ;
head x = case x of {
Cons h _ => h ;
};
repeat : Int -> Int -> List () ;
repeat x n = case n of {
0 => Nil ;
n => Cons x (repeat x (n + minusOne)) ;
};
minusOne : Int ;
minusOne = 9223372036854775807 + 9223372036854775807 + 1;
-- take the length of a list
length : List () -> Int ;
length x = case x of {
Cons _ xs => 1 + length xs ;
Nil => 0 ;
};
-- sum a list
sum : List () -> Int ;
sum x = case x of {
@ -36,3 +56,17 @@ sum x = case x of {
-- sum + length of a list
sumlength: List () -> Int ;
sumlength x = sum x + length x ;
-- take the head of a list
head : List () -> Int ;
head x = case x of {
Cons h _ => h ;
};
-- repeat an element n times
repeat : Int -> Int -> List () ;
repeat x n = case n of {
0 => Nil ;
n => Cons x (repeat x (n + minusOne)) ;
};
-}