Gloria95
Gloria95

Reputation: 139

How can I create my own list in Haskell?

I would like to create my own list in Haskell where I could put in the number 6 and get the result [1,2,3,4,5,6]

I thought I could write something like

ones :: Int ->  [a]
ones 0 = []
ones n = [n, n-1 ... n==0]

Could someone help me?

Upvotes: 0

Views: 296

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

There are many ways to do this. Below a non-exhaustive list.

You can use Haskells list ranges:

ones :: (Enum n, Num n) -> n -> [n]
ones n = [1 .. n]

You can use the enumFromTo :: Enum a => a -> a -> [a] function:

ones :: (Enum n, Num n) -> n -> [n]
ones = enumFromTo 1

Or we can use explicit recursion:

ones :: (Ord n, Num n) => n -> [n]
ones n = go 1
    where go i | i <= n = i : go (i+1)
               | otherwise = []

Or by using iterate :: (a -> a) -> a -> [a] and take :: Int -> [a] -> [a]:

ones :: Num n => Int -> [n]
ones n = take n (iterate (1+) 1)

Note that not all approaches have the same signature. Some implementations do not require the numerical type to be an instance of the Enum type class, which can make the function more flexible in the sense that numerical types that can not be enumerated, can still get processed.

Upvotes: 5

Related Questions