Search code examples
listhaskellcounterincrement

Generating Simple List from 1 to 10 with haskell


I am new in Haskell, could guys help me how to generating list from 1 to 10.

I tried to make like this:

seqList :: Integer -> [Integer]
seqList 1 = [1]
seqList n = n : seqList(n-1)

The result 10 to 1, not 1 to 10

And second question can we make function as value.

numList :: [Integer]
numList =  [1,2..10]
totJum :: Int
totJum = length numList

takeNum :: Int->[Integer]
takeNum totJum
  | totJum >= 10 = take 5 numList
  | totJum == 10  = numList

With this code, i want to call output if the length from numlist matches the condition.


Solution

  • For the first one you can work with an accumulator: a variable you use to yield a value and each time increment in the recursive call, so:

    seqList :: Integer -> [Integer]
    seqList n = go 1
        where go i
                  | i <= … = …
                  | otherwise = …

    where I leave filling in the parts as an exercise.

    with this code, I want to call output if the length from numlist matches the condition.

    You should not use totJum as a parameter, but just use it in the body of the function, so:

    takeNum :: [Integer]
    takeNum
      | totJum >= 10 = take 5 numList
      | totJum == 10  = numList
    

    Note however that here you do not cover the case where totJum is less than or 10. In that case the function will thus error. You thus might want to add an otherwise clause.