|Perl Monk, Perl Meditation|
Re^16: World's shortest intro to function programmingby kelan (Deacon)
|on Jun 21, 2005 at 14:44 UTC||Need Help??|
I'd just really like to see a reasonably simple but complete program developed from start to finish, by a competent Haskell programmer, as a way of getting a step up into the use of the language.
You may have seen this already, but nothingmuch was also fed-up with having no real-world examples in the Haskell tutorials. So to help himself learn, and maybe help out the other like-minded imperative programmers, he's developing a Forth compiler targetting Parrot, in a tutorial-like format. It starts off simple and builds up, so it's not too difficult to follow. Give it a look if you haven't already.
Simple example: When should I use data, when type or newtype?
The Anonymous Monk's reply to this question is clear and concise, but for anyone following along that doesn't know C, here's a more verbose answer.
type is just for creating a type-synonym. It doesn't really create a new type, but it can make your code easier to understand by giving a more meaningful name to an existing type. For example:
In the above, the types Name and String can be used interchangeably, but using Name appropriately can make the code's intent clearer.
data is for defining a completely new type. This confused me at first, too, because the keyword data doesn't seem to relate to types. I'm guessing that the reason for that keyword is because this construct is used to define the data constructors for the type. Example:
And data constructors can take parameters, and each can take different numbers of parameters:
Probably what confused me the most about the data construct when I started learning it was that the examples used the same word for the typename and the data constructor, so it was unclear that they are actually separate ideas.
newtype, as the Anonymous Monk said, is the same as data, except there can be only one data constructor, and it gets optimized away for lower overhead.
A reference I found helpful when learning about type and data was Tour of the Haskell Syntax, which gives the actual syntax in a clear and concise form.