Skip to content

Instantly share code, notes, and snippets.

@lironsade
Created November 15, 2018 17:52
Show Gist options
  • Save lironsade/bfa2a46ac7d415d7c6e7d4efe8fc13b6 to your computer and use it in GitHub Desktop.
Save lironsade/bfa2a46ac7d415d7c6e7d4efe8fc13b6 to your computer and use it in GitHub Desktop.
data BinaryOp = Plus | Minus | Mult | Div | Pow deriving (Show, Eq)
data UnaryOp = Sin | Cos deriving (Show, Eq)
data Tree a = Empty | BTree (Tree a) BinaryOp (Tree a) | UTree UnaryOp (Tree a) | Const a | Var deriving (Show)
eval :: (Floating a) => Tree a -> a -> Maybe a
eval Empty _ = Just 0
eval Var x = Just x
eval (Const a) _ = Just a
eval (BTree left op right) x
| op == Plus = (+) <$> (eval left x) <*> (eval right x)
| op == Minus = (-) <$> (eval left x) <*> (eval right x)
| op == Mult = (*) <$> (eval left x) <*> (eval right x)
| op == Div = (/) <$> (eval left x) <*> (eval right x)
| op == Pow = (**) <$> (eval left x) <*> (eval right x)
eval (UTree op left) x
| op == Sin = sin <$> (eval left x)
| op == Cos = cos <$> (eval left x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment