[Haskell-beginners] Re: [Haskell-cafe] represent data sturcture using function

David Menendez dave at zednenem.com
Mon Dec 29 01:13:54 EST 2008

2008/12/29 Raeck chiu <raeck at msn.com>:
> People sometime will try to represent a quantity-regard-only data structure
> (such a order-regadless List) using functions instead of ta concrete data
> structure (like the haskell build-in []), any particular reason for this?
> For example,
>> data Sex = Male | Female
>> classA :: Sex -> Int
>> classA Male = 100
>> classA Female = 200
> when I should prefer the above solution instead of using a concrete data
> structure such as [] to represent the classA members?

One important difference between Sex -> Int and [(Sex,Int)] is that
the first guarantees exactly one Int per Sex and has no underlying
order. (That is, [(Male,100),(Female,200)] and
[(Female,200),(Male,100)] are distinct lists but represent the same

> It seems to be very difficult to change the number of Male or Female if a
> concrete data structure is not used. Is it possible change the number of Male in classA
> when represent classA using function?

Here's the simplest way:

    update k v map = \k' -> if k' == k then v else map k'

Note that it requires an Eq instance for Sex.

    let classA' = update Male 150 classA
    in (classA' Male, classA' Female)

Dave Menendez <dave at zednenem.com>

More information about the Beginners mailing list