View Patterns

This is the first blog post in an effort to try and improve my understanding of various facets of Haskell. Collectively, they are really just an attempt on my part of refine and improve my understanding of Haskell by trying to explain it to someone else. Haskell has a certain impenetrability which is compounded by the fact that there are many language extensions which apparently add greatly to your productivity but at the same time change the syntax or introduce a new layer of category-theory abstraction to your programs.

It’s all good - Haskell is an amazing language - but for me, trying to understand it takes a little more effort than it does with some of the other more popular languages.

View Patterns

This is a review of the View Patterns extension, and is itself based on a different review by Oliver Charles, so if this seems in any way confusing then you can always check his blog post out. Also, if my analysis is just wrong then please feel free to let me know in the comments.

What is a View Pattern?

A View Pattern is augmentation of the normal pattern matching functionality in Haskell that allows you to pattern match against the output of function. For example, let’s say that you want to take a specific course of action based on the presence of a value in a list:

import Data.List

-- possibly the most contrived example every devised!
main = do
if containsKey 1 [(1,"a"),(2,"b"),(3,"c")] then printLn "found" 
                                           else printLn "missing"

containsKey :: a -> [(a,b)] -> Bool
containsKey x xs = case lookup x xs of
                     Nothing -> False
                     Just _     -> True

Now, dispensing with the fact that I am cringing in my seat at using such a silly example, let’s look at how View Patterns can be applied to this code:

{-# LANGUAGE ViewPatterns #-}

import Data.List

-- possibly the most contrived example every devised!
main = do
if containsKey 1 [(1,"a"),(2,"b"),(3,"c")] then printLn "found" 
                                           else printLn "missing"

containsValue :: a -> [a] -> Bool
containsValue x (lookup x -> Nothing) = False
containsValue x (lookup x -> Just _) = True

So what we have done is to move the case statement into the pattern match.

This can be made more sophisticated. There are several more complex examples given in the Haskell specification for ViewPatterns.

Written with StackEdit.

Comments

Popular Posts