[Haskell-cafe] Re: [Haskell] View patterns in GHC: Request for feedback

apfelmus apfelmus at quantentunnel.de
Wed Jul 25 05:28:22 EDT 2007


Jules Bean wrote:
> Have you tried using pattern guards for views?
> 
> f s | y :< ys <- viewl s = ....
>     | EmptyL  <- viewl s = ....

Hm, I'd simply use a plain old case-expression here

  f s = case viewl s of
     y :< ys -> ...
     EmptyL  -> ...

In other words, case-expressions are as powerful as any view pattern may
be in the single-parameter + no-nesting case.


A better example is probably  zip  for sequences (Data.Sequence.Seq):

  zip :: Seq a -> Seq b -> Seq (a,b)
  zip xs ys = case viewl xs of
     x :< xt -> case viewl ys of
         y :< yt -> (x,y) <| zip xt yt
         EmptyL  -> empty
     EmptyL  -> empty

Pattern guards

  zip xs ys
    | EmptyL <- viewl xs = empty
    | EmptyL <- viewl ys = empty
    | x :< xt <- viewl xs, y :< yt <- viewl ys = (x,y) <| zip xt yt

Pattern guards variant

  zip xs ys
    |  EmptyL <- xs'                 = empty
    |                  EmptyL <- ys' = empty
    | x :< xt <- xs', y :< yt <- ys' = (x,y) <| zip xt yt
    where
    xs' = viewl xs; ys' = viewl ys

View patterns

  zip (viewl -> EmptyL) _  = empty
  zip _  (viewl -> EmptyL) = empty
  zip (viewl -> x :< xs) (viewl -> y :< ys) = (x,y) <| zip xs ys

My dream

  zip EmptyL  _       = empty
  zip _       EmptyL  = empty
  zip (x:<xs) (y:<ys) = (x,y) <| zip xs ys


Regards,
apfelmus



More information about the Haskell-Cafe mailing list