candpythonprogrammer
candpythonprogrammer

Reputation: 95

Couldn't match expected type [Int] Haskell

I am new to Haskell so I don't quite understand most of its errors. I have encountered an error trying to make a higher order function that uses foldl() to read a list and then multiply it by 2 (it automatically reverses it) and I use another another foldl() just to read it, in so reversing it to its original order.

I would be thankful for any help I receive.

here's the error

 • Couldn't match expected type ‘[Int]’
                  with actual type ‘t0 Integer -> [Integer]’
    • Probable cause: ‘foldl’ is applied to too few arguments
      In the first argument of ‘reverses’, namely
        ‘(foldl (\ acc x -> (2 * x) : acc) [])’
      In the expression: reverses (foldl (\ acc x -> (2 * x) : acc) [])
      In an equation for ‘multthr’:
          multthr = reverses (foldl (\ acc x -> (2 * x) : acc) [])
   |
16 | multthr = reverses(foldl(\acc x-> (2*x):acc)[])
   |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^

here's the source code

reverses::[Int] ->[Int]
reverses = foldl(\acc x-> x:acc)[]

multthr::[Int]->([Int]->[Int])
multthr = reverses(foldl(\acc x-> (2*x):acc)[]) 

Upvotes: 1

Views: 367

Answers (1)

Will Ness
Will Ness

Reputation: 71099

You need to compose your two foldl's with (.), instead of applying one to the other:

reverses :: [a] -> [a]
reverses = foldl (\acc x-> x:acc) []

---- multthr :: [Int] -> ([Int] -> [Int])  -- why??
multthr :: [Int] -> [Int]
---- multthr = reverses (foldl(\acc x-> (2*x):acc)[])  -- causes error
multthr = reverses . foldl (\acc x-> (2*x):acc) [] 

so that we have

> multthr [1..5]
[2,4,6,8,10]
it :: [Int]

(.) is the functional composition, defined as (f . g) x = f (g x).

Instead of doing the two foldl's you can do one foldr,

mult2 = foldr (\x r -> (2*x) : r) []

but then this is nothing else but, simply, map (2*).

Upvotes: 3

Related Questions