Advertisement
NLinker

arrange and pattern matching

Oct 27th, 2016
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- arrange expression for a _associative_ operation type
  2. -- (therefore ot can be either + or *); examples:
  3. -- (a+(b+c)+d) -> (((a+b)+c)+d), where a, b, c, d are not Add operations
  4. -- (a*(b*c)*d) -> (((a*b)*c)*d), where a, b, c, d are not Mul operations
  5. --    o1                o2
  6. --   / \               / \
  7. --  a  o2      =>     o1 b2
  8. --     / \           / \
  9. --    b1 b2         a  b1
  10. arrange :: Expr -> Expr
  11. -- arr a | trace ("arr " ++ show a) False = undefined
  12. arrange n@Nm{} = n
  13. arrange ex@(Op _o _a@Nm{} _b@Nm{}) = ex
  14. arrange (Op  o  a@Op{}  b@Nm{}) = Op o (arrange a) b
  15. arrange (Op o1 a b@(Op o2 b1 b2)) = case (o1, o2) of
  16.   (Add, Add) -> arrange regroup
  17.   (Add, Sub) -> arrange regroup
  18.   (Mul, Mul) -> arrange regroup
  19.   (Mul, Div) -> arrange regroup
  20.   _          -> Op o1 (arrange a) (arrange b)
  21.   where
  22.     regroup = Op o2 (Op o1 a b1) b2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement