Try this new stackoverflow thing as suggested :) This is not a very specific haskell, but it is clear in haskell.
Here is a pattern that appears every time and time: the function takes two arguments, which it processes symmetrically. this property often happens. Example:
-- | Merge sorted lists of ranges. merge :: (Ord n) => [(n, n)] -> [(n, n)] -> [(n, n)] merge [] r2 = r2 merge r1 [] = r1 merge r1@((s1, e1) : rest1) r2@((s2, e2) : rest2) | e1 < s2 = (s1, e1) : merge rest1 r2 | e2 < s1 = (s2, e2) : merge r1 rest2 | s1 >= s2 && e1 <= e2 = merge rest1 r2 -- 1 within 2 | s2 >= s1 && e2 <= e1 = merge r1 rest2 -- 2 within 1 | e1 > e2 = merge (merged : rest1) rest2 | otherwise = merge rest1 (merged : rest2) where merged = (min s1 s2, max e1 e2)
Note that the processing of "r1" and "r2" is symmetric. In fact, there are only 4 cases: combining with a zero value results in a non-empty, not a coincidence, gives the range unchanged, one of which contains the other range, and the overlap creates a combined range and tries to combine it with the rest.
However, each case has a mirror version, so it ends with 8, although mirror 4 can be obtained mechanically. Not only is there twice as much room for errors, due to symmetry errors will not be caught by the typechecker director. Is there a name for this template? Ways to cancel a repeat? I suppose I can try to define it for a list and then write "mappend ab = mconcat [a, b]", but the problem is that itβs more difficult for me to think in a general way (for example, it hurts me to remember which list to include again combined interval). It is much easier to define mappend and then get mconcat from this. Maybe there is a better way to think about a list version to avoid headaches?
What I think I want to do is βfocusβ on one case, so I can write in terms of βthisβ and βthatβ. Not only is it easier to think than two equally privileged βr1β and βr2β, that-> this case should be implicit from this-> this.
design pattern-matching haskell
Evan laforge
source share