Skip to content

Instantly share code, notes, and snippets.

@lironsade
Created November 19, 2018 12:07
Show Gist options
  • Save lironsade/c4e9b6e9ad1565374fdeb92d6cad5654 to your computer and use it in GitHub Desktop.
Save lironsade/c4e9b6e9ad1565374fdeb92d6cad5654 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, Eq 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 right x) == (Just 0) = Nothing
| 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)
deriv :: (Floating a) => Tree a -> Tree a
deriv Empty = Empty
deriv (Const a) = Const 0
deriv Var = Const 1
deriv (BTree left op right)
| op == Plus = BTree (deriv left) Plus (deriv right)
| op == Minus = BTree (deriv left) Minus (deriv right)
| op == Mult = BTree (BTree (deriv left) Mult right) Plus (BTree left Mult (deriv right))
| op == Div = BTree (BTree (deriv left) Mult right) Plus (BTree left Mult (deriv right))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment