Insufficient definition of replication
I have a question that I find quite difficult.
The standard prelude contains the function
replicate :: Int -> a -> [a]
The following may seem like a reasonable definition to him
replicate n x = take n [x,x,..]
But in reality this is not enough. Why not?
I know the function replicate
is defined as:
replicate :: Int -> a -> [a]
replicate n x = take n (repeat x)
And it is repeat
defined as:
repeat :: a -> [a]
repeat x = xs where xs = x:xs
Is the definition insufficient (from the question) because it uses an infinite list?
source to share
First of all, there is a small syntax error in the question, it should be:
replicate n x = take n [x,x..]
-- ^ no comma
but don't be picky.
Now that you are using the range syntax (i.e. x..
) then x
must have a type that is an instance Enum
. Really:
Prelude> :t \n x -> take n [x,x..] \n x -> take n [x,x..] :: Enum a => Int -> a -> [a]
One could argue that it x,x..
will only generate x
, but the Haskell compiler doesn't know that at compile time.
So the type in replicate
(in the question) is too specific : it implies a type constraint - Enum a
- it's actually unnecessary.
Its own definition, on the other hand, is fine. Haskell has no problem with infinite lists as it uses lazy evaluation. Also, since you define xs
c xs
as a tail, you've actually created a circular linked list, which is also better in terms of memory usage.
source to share