Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- data Op = Add | Sub | Mul | Div
- data Expr = Val Int | App Op Expr Expr
- valid :: Op -> Int -> Int -> Bool
- valid Add _ _ = True
- valid Sub x y = x > y
- valid Mul _ _ = True
- valid Div x y = x `mod` y == 0
- apply :: Op -> Int -> Int -> Int
- apply Add x y = x + y
- apply Sub x y = x - y
- apply Mul x y = x * y
- apply Div x y = x `div` y
- eval :: Expr -> [Int]
- eval (Val n) = [n | n > 0]
- eval (App o l r) = [apply o x y | x <- eval l,
- y <- eval r,
- valid o x y ]
- -- so for example if i run:
- eval (App Add (Val 1) (Val 9))
- -- i will get 10
- -- (the validity check is OK. i just add them together.)
- -- what i dont understand is why this return the empty list?
- eval (App Add (Val 1) (App Sub (Val 2) (Val 3)))
- -- so at first in the list comprehension 'x' gets (Val 1) (which evaluate to 1) and the 'y' is translated to
- eval (App Sub (Val 2) (Val 3))
- {-
- and then in the list comprehension there 'x' will be
- (Val 2) (which translate to 2) and 'y' will be (Val 3) (which translate to 3).
- the validity here get 'False' because 2 - 3 is negative number and we not allow it.
- so as i understand i get back the empty list.
- so now back to the first list comprehension, 'x' is still 2 but now 'y' is [].
- and this is what i don't understand:
- why i eventually get back the empty list?
- is it because the function 'eval' that takes 'Expr' which only gets:
- -}
- Val Int | App Op Expr Expr
- {-
- (and here i get the empty list in the second 'Expr' which can't be because the empty list), is not an 'Expr'?
- i understand that i can't Add together 'Expr' and [] (it's not in the type signature).
- but why i don't recieve an error if it's not in the type signature?
- why i get the empty list without error?
- -}
Advertisement
Add Comment
Please, Sign In to add comment