[Haskell-beginners] how to define records containing finite length lists.

Stephen Tetley stephen.tetley at gmail.com
Tue Dec 1 13:26:45 EST 2009


Choices, choices...

Firstly, C uses an array not a list so you can too:

> data Person = Person{
>      name :: UArray Int Char,
>      age :: Int
>   }
>   deriving (Show)

Of course there is no bound on the type to be of length 10, the length
would be bound at creation time:

> stephen = Person { name = array (0,9) (zip [0..] "stephen")
>                  , age  = 0
>                  }

Quite horrible - but not significantly worse than C unless you believe
the array size declator is defining the array type rather than just
its storage size. Hmm.

Sized types are a possibility but are quite advanced, certainly they
give more 'static guarantees' than C provides (or just about anything
else except dependent-types...).

One example is here e.g:
http://hackage.haskell.org/package/sized-types

Tuples are another possibility but quite unwieldy: no special syntax,
you would need to write conversion functions:

> type Name = (Char,Char,Char,Char,Char,Char,Char,Char,Char,Char)


You could wrap a String inside a newtype and provide a special constructor,
hiding the Name10 constructor via a module:


> newtype Name10 = Name10 { getName10 :: String }


> makeName10 :: String -> Name10
> makeName10 s | length s > 10 = Name10 $ take 10 s
>              | otherwise     = Name10 s    -- pad if you like here



Essentially it depends what you want to do with the sized string -
generally you will loose string syntax[*] and all the list processing
functions that work on strings as they are just lists of Char. This
might not be a good balance for the safety you want.

Best wishes

Stephen


[*] But you can overload string syntax for nefarious purposes (adding
more complexity):
http://www.haskell.org/ghc/docs/latest/html/users_guide/type-class-extensions.html#overloaded-strings

2009/12/1 Srikanth K <k.srikanth.opensource at gmail.com>:
> Hi,
>    I want to define a record say "Student".  The 'C' equvivalent for the
> same could be
>
> struct Person {
>      char name[10]
>      int age }
>
> The closest I can find for doing such a thing in haskell appears to be
>
> data Person = Person{
>      name :: [char]
>      age :: Int
> }
>
> I have not yet been able to find a suitable way to specify the constraint on
> the length of list(name in this case).
> So can someone let me know how we can impose this length constratint on the
> list  and derive a new type.
>
> If standard haskell doesn't give this flexibility, are there any extensions
> in ghc to achieve the same.
> - Srikanth
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
>


More information about the Beginners mailing list