0

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?

2
  • 4
    ones n = [1..n] Commented Aug 9, 2018 at 9:13
  • 3
    Why would you call this function ones? Commented Aug 9, 2018 at 13:02

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I think unfoldr is worth mentioning. Also, Num isn't strictly more general than Enum, as things like Ordering and Bool show.
scanl is f n = scanl (\b a -> b+a) 1 $ replicate (n-1) 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.