Reputation: 41
In Haskell programming language, how can we produce an infinite list of identical elements.What is the code in Haskell in which user inputs some number and infinite list of that number generated. I had practiced but it was not successful. My logic is below: Code:
repeat :: a -> [a]
repeat x = xs where
xs=x*xs
Upvotes: 2
Views: 2117
Reputation: 476574
You are quite close, but the strange thing here is that you write x*xs
, (*)
is an operator that is usually used to multiply numbers, it is a function that is a method of the Num
typeclass.
In case you construct a list, you use the list data constructors. The two data constructors are [] :: [a]
(the empty list), and (:) :: a -> [a] -> [a]
. Here it makes sense to use the (:)
operator: we prepend xs
with x
, so we can write:
repeat :: a -> [a]
repeat x = xs
where xs = x : xs
Here we thus construct for a given x
parameter, a linked list that looks like:
+-------+
| (:) |<-.
+---+---+ |
| o | o | |
+-|-+-|-+ |
v `----'
x
So a "cons" element where the tail refers to itself. As a result if you perform some list processing, it is possible that the memory usage remains constant (without garbage collection) and Haskell thus keeps looping in the same cons object.
Upvotes: 9