sholizar

Untitled

Mar 28th, 2018
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. data Op = Add | Sub | Mul | Div
  2.  
  3. data Expr = Val Int | App Op Expr Expr
  4.  
  5. valid :: Op -> Int -> Int -> Bool
  6. valid Add _ _ = True            
  7. valid Sub x y = x > y            
  8. valid Mul _ _ = True            
  9. valid Div x y = x `mod` y == 0
  10.  
  11. apply :: Op -> Int -> Int -> Int
  12. apply Add x y = x + y    
  13. apply Sub x y = x - y    
  14. apply Mul x y = x * y    
  15. apply Div x y = x `div` y
  16.  
  17. eval :: Expr -> [Int]
  18. eval (Val n) = [n | n > 0]
  19. eval (App o l r) = [apply o x y | x <- eval l,
  20.                                   y <- eval r,
  21.                                   valid o x y ]
  22.  
  23.  
  24. -- so for example if i run:
  25. eval (App Add (Val 1) (Val 9))
  26. -- i will get 10
  27. -- (the validity check is OK. i just add them together.)
  28.  
  29. -- what i dont understand is why this return the empty list?
  30.  
  31. eval (App Add (Val 1) (App Sub (Val 2) (Val 3)))
  32.  
  33.  
  34. -- so at first in the list comprehension 'x' gets (Val 1) (which evaluate to 1) and the 'y' is translated to
  35. eval (App Sub (Val 2) (Val 3))
  36. {-
  37. and then in the list comprehension there 'x' will be
  38. (Val 2) (which translate to 2) and 'y' will be (Val 3) (which translate to 3).
  39. the validity here get 'False' because 2 - 3 is negative number and we not allow it.
  40. so as i understand i get back the empty list.
  41. so now back to the first list comprehension, 'x' is still 2 but now 'y' is [].
  42. and this is what i don't understand:
  43. why i eventually get back the empty list?
  44. is it because the function 'eval' that takes 'Expr' which only gets:
  45. -}
  46. Val Int | App Op Expr Expr
  47. {-
  48. (and here i get the empty list in the second 'Expr' which can't be because the empty list), is not an 'Expr'?
  49. i understand that i can't Add together 'Expr' and [] (it's not in the type signature).
  50. but why i don't recieve an error if it's not in the type signature?
  51. why i get the empty list without error?
  52. -}
Advertisement
Add Comment
Please, Sign In to add comment