Home > Mobile >  Can't get the length of a list in Haskell
Can't get the length of a list in Haskell

Time:01-21

I am new to Haskell and I am trying to get the length of a list created by a function. I am getting this error and I don't understand what it means:

    * Couldn't match expected type `t1 -> a0' with actual type `Int'
    * The function `length' is applied to two value arguments,
        but its type `(Int -> [String]) -> Int' has only one
      In the first argument of `print', namely `(length strings 1)'
      In a stmt of a 'do' block: print (length strings 1)
  |
9 |     print(length strings 1)
  |           ^^

Calling the function by using print (strings 1) works so I don't understand why I can't get the length of it.

strings :: Int -> [ String ]
strings 0 = [""] 
strings n = concat ( map (\x -> map (\ tail -> x: tail ) tails ) ['a'.. 'z'])
    where tails = strings (n -1)

main :: Int main = do
    print(length strings 1)

CodePudding user response:

length strings 1 means you apply the function length to the arguments strings and 1. In other languages that would be written length(strings, 1). But 1 is supposed to be the argument to strings instead, so you should write one of the following instead:

print (length (strings 1))
print (length $ strings 1)
print $ length $ strings 1
print . length $ strings 1    -- recommended version
(print . length . strings) 1
  •  Tags:  
  • Related