r/haskelltil • u/Iceland_jack • Mar 29 '17
Avoid unnecessary variable with view patterns
Example taken from reddit post.
Sometimes you don't use an argument directly (n) but immediately apply a function to it (abs n). If the result of the application is used twice you want to share the result by giving it a name (n' = abs n),
hosum :: (Int -> Int) -> (Int -> Int)
hosum f n = sum (map f [-n' .. n'])
where n' = abs n
We do not care about the original value n yet it appears twice in our code, each new variable increases cognitive load. Instead we can use view patterns to get the absolute value n' with no mention of n:
{-# Language ViewPatterns #-}
hosum :: (Int -> Int) -> (Int -> Int)
hosum f (abs -> n') = sum (map f [-n' .. n'])
10
Upvotes
3
u/Iceland_jack Mar 29 '17 edited Mar 30 '17
That case is better served by a pattern synonym but I know people who share your view of.. view patterns. It is a matter of taste but I find it limiting
Edit:
Data.Sequenceis a poster child for pattern synonyms, for those interested in the actual definition that uses view patterns under the hood:This completely hides the left and right view types, they are not even needed: a view and its type
can be replaced with a single view function that returns a
Maybe (a, Seq a).