[Haskell-beginners] About repeat function
Christopher Done
chrisdone at googlemail.com
Fri Jun 24 10:56:33 CEST 2011
On 24 June 2011 10:31, divyanshu ranjan <idivyanshu.ranjan at gmail.com> wrote:
> My question is why it produces list in first place. 1:2:3 is not a list but
> 1:2:3:[] is. How comes haskell know that the things which we are adding will
> eventually added to the beginning of empty list given things are infinite
> so you can specify the end which is [] . Then why doing 1:3:4 is not
> acceptable ?
It's quite simple if you consider that it's just based on types of
expressions and nothing more.
Consider the type of the (:) function:
(:) :: x -> [x] -> [x]
It takes x and list of x. So we can write:
() : []
And the expression () : [] has type [()]
Therefore we can also take that and put it on the right-hand side again:
() : (() : [])
See how () and (() : []) fit into the x and [x] places in the (:) function?
Continuing:
() : (() : (() : []))
And so on. The (:) function is right-associative (meaning x : b : c :
d means x : (b : (c : d))). So we don't need the parentheses, the
following is equivalent to the previous:
() : () : () : []
The a:b:c syntax isn't special in any way. But you should always
implicitly read it as (a:(b:c)), remembering that everything on the
left-hand side of a : is type x, and everything on right-hand side is
[x].
repeat' x has type [x], so you can write x : repeat x
E.g. consider manually evaluating repeat () on paper, we'd write out:
repeat ()
() : repeat ()
() : () : repeat ()
() : () : () : repeat ()
And so on. It will go on forever if you keep evaluating the end
expression. Haskell is lazy, so we don't have to evaluate the
right-hand side if we don't want use it. But the type of the
expressions, you should observe, are always correct.
The reason 1:3:4 is not acceptable is because 4 is not of type [x],
whereas 1:3:repeat 4 would be because repeat 4 is of type [x].
Ciao!
More information about the Beginners
mailing list