[Haskell-beginners] Type Class Woes ..
Daniel Fischer
daniel.is.fischer at web.de
Sun Aug 30 09:06:02 EDT 2009
Am Sonntag 30 August 2009 14:32:56 schrieb Patrick LeBoutillier:
> Hi,
>
> volume :: Fruit FruitType -> Double
>
> > volume F{radius=r,len=l,fType=Orange} = (4.0/3.0) * pi * r * r * r
> >
> >
> > volume F{radius=r,len=l,fType=Apple} = (4.0/3.0) * pi * r * r * r
> > volume F{radius=r,len=l,fType=Banana} = pi * (r * r) * l
> > volume F{radius=r,len=l,fType=Watermelon} = (4.0/3.0) * pi * (2.0 * r)
> > * l * (0.5 * l)
>
> Can anyone explain the above pattern matching syntax? I've never seen it
> before...
>
>
> Thanks,
>
> Patrick
It's named-field syntax, cf.
http://haskell.org/onlinereport/exps.html#sect3.15
If you have a type with named fields, like
data FType
= Con1 { field1 :: Int, field2 :: Bool }
| Con2 { field1 :: Int, field3 :: Char }
you can pattern-match either by position:
fun (Con1 i b) = ...
or by named field syntax:
fun Con1{field2=True, field1=x} = ... -- corresponds to fun (Con1 x True)
fun Con2{field3='a'} = ... -- fun (Con2 _ 'a')
It's very convenient if you need only a few arguments of a multi-argument constructor:
fun C{fieldx=y}
vs.
fun (C _ _ _ _ _ y _ _ _ _)
More information about the Beginners
mailing list