From 870aad52cfcd1770695bcfca72e3edac01c3bd04 Mon Sep 17 00:00:00 2001 From: darkf Date: Fri, 18 Oct 2013 13:49:33 -0700 Subject: [PATCH] add cons patterns --- interp.hs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/interp.hs b/interp.hs index 73ec0cf..86ee03b 100644 --- a/interp.hs +++ b/interp.hs @@ -13,6 +13,7 @@ data AST = Add AST AST data Pattern = VarP String | IntP Int + | ConsP Pattern Pattern deriving (Show, Eq) data Value = IntV Int @@ -68,11 +69,19 @@ eval (Call name args) = get >>= \m -> patternBindings :: Pattern -> Value -> Maybe Env patternBindings (VarP n) v = Just $ M.fromList [(n, v)] + patternBindings (IntP n) (IntV v) | v == n = Just M.empty | otherwise = Nothing patternBindings (IntP n) _ = Nothing +patternBindings (ConsP _ _) (ListV (_:[])) = Nothing +patternBindings (ConsP xp xsp) (ListV (x:xs)) = + do + xe <- patternBindings xp x + xse <- patternBindings xsp $ ListV xs + Just $ M.union xe xse + -- applies many arguments to a function applyMany :: Value -> [Value] -> InterpState Value applyMany fn@(FnV _) (arg:xs) = @@ -118,4 +127,8 @@ main = do (VarP "x", [IntConst 300]) ], Call "f" [IntConst 2]] - prg4 = [ Def "lst" (ListConst [IntConst 1, IntConst 2, IntConst 3]) ] \ No newline at end of file + prg4 = [ Def "lst" (ListConst [IntConst 1, IntConst 2, IntConst 3]), + Def "f" $ Lambda [ + (ConsP (VarP "x") (ConsP (VarP "y") (VarP "ys")), [Var "ys"]) + ], + Call "f" [Var "lst"]] \ No newline at end of file