Creating an infinite list from ADT

In Haskell

> a = [1,1..] 

creates an endless list. I now have the following

 data Subunit = O | P deriving (Eq, Show) 

And if I do

 b :: [Subunit] b = take 6 [P,P..] 

I get the following:

  parse error on input ']' 

Why does this fail? What do I need to add to create an endless list?

+5
source share
5 answers

Good booty! Indeed, he is mistaken ...

 > take 10 [P, P..] <interactive>:6:16: parse error on input ']' 

... But it is not

 > take 10 [P, P ..] -- one more space [P,P,P,P,P,P,P,P,P,P] 

Why are the gaps significant? Because otherwise, the syntax overlaps with prefixed names of the modules, which are of the form Module.name . Here, for example, refers to the operator . from Prelude .

 > :t (Prelude..) (Prelude..) :: (b -> c) -> (a -> b) -> a -> c > :t succ Prelude.. succ -- infix use! succ Prelude.. succ :: Enum c => c -> c 

Therefore, P.. is . from the module P , and P .. works great in listing the list.

(Yes, this is a bad syntax quirk ...)

+10
source

[n,n'..] is the syntax sugar for enumFromThen , so you need your type, which is an instance of the Enum class type.

You will also need a value, not a value constructor :

 \> data Subunit = O | P deriving (Eq, Show, Enum) \> let a = P \> take 6 [a,a..] [P,P,P,P,P,P] 

or (for comment @ sepp2k):

 \> take 6 [P,P ..] -- ^ space [P,P,P,P,P,P] 
+3
source

as an alternative to behzads you can do

 b :: [Subunit] b = take 6 $ repeat P 

too - this doesn't need Enum

+3
source

You can use this line to create an infinite list of ADTs.

 infiniteSubunit = P:infiniteSubunit 

Then you can use it as is.

 b :: [Subunit] b = take 6 infiniteSubunit 
+1
source

As another alternative, to do what you want to do directly, use

 b :: [Subunit] b = replicate 6 P 
+1
source

Source: https://habr.com/ru/post/1241052/


All Articles