Are pattern guards obsolete?
Donald Bruce Stewart
dons at cse.unsw.edu.au
Sun Dec 10 19:04:48 EST 2006
schneegloeckchen:
> Hello,
>
> recently I read about pattern guards which are a candidate for Haskell'.
>
> As I understand them, their purpose is to provide an easier way to write
> functions like (taken from the wiki, it does not run):
>
> clunky env var1 var1 = case lookup env var1 of
> Nothing -> fail
> Just val1 -> case lookup env var2 of
> Nothing -> fail
> Just val2 -> val1 + val2
> where
> fail = var1 + var2
>
>
> Wouldn't
>
> > clunky :: Num a => [(a, a)] -> a -> a -> a
> > clunky env var1 var2 = case (lookup var1 env, lookup var2 env) of
> > (Just v1, Just v2) -> v1 + v2
> > _ -> var1 + var2
>
> be simple enough to make a syntax change superflous? It is so simple, that there
> is no need for `fail` in Haskell or Haskell' :)
There's been a previous discussion on this[1]. The joy of pattern guards
reveals once you have more conditions. Consider this real world example:
clean_ s| Just _ <- no_io `matchRegex` s = "No IO allowed\n"
| Just _ <- terminated `matchRegex` s = "Terminated\n"
| Just _ <- hput `matchRegex` s = "Terminated\n"
| Just _ <- outofmem `matchRegex` s = "Terminated\n"
| Just _ <- stack_o_f `matchRegex` s = "Stack overflow\n"
| Just _ <- loop `matchRegex` s = "Loop\n"
| Just _ <- undef `matchRegex` s = "Undefined\n"
| Just _ <- type_sig `matchRegex` s = "Add a type signature\n"
| Just (_,m,_,_) <- ambiguous `matchRegexAll` s = m
| Just (_,_,b,_) <- inaninst `matchRegexAll` s = clean_ b
| Just (_,_,b,_) <- irc `matchRegexAll` s = clean_ b
| Just (_,m,_,_) <- nomatch `matchRegexAll` s = m
| Just (_,m,_,_) <- notinscope `matchRegexAll` s = m
| Just (_,m,_,_) <- hsplugins `matchRegexAll` s = m
| Just (a,_,_,_) <- columnnum `matchRegexAll` s = a
| Just (a,_,_,_) <- extraargs `matchRegexAll` s = a
| Just (_,_,b,_) <- filename' `matchRegexAll` s = clean_ b
| Just (a,_,b,_) <- filename `matchRegexAll` s = a ++ clean_ b
| Just (a,_,b,_) <- filepath `matchRegexAll` s = a ++ clean_ b
| Just (a,_,b,_) <- runplugs `matchRegexAll` s = a ++ clean_ b
| otherwise = s
-- Don
1. http://www.haskell.org/pipermail/haskell-prime/2006-September/001689.html
More information about the Haskell-prime
mailing list