简体   繁体   中英

Error while trying folding(foldr()) in Haskell

I am struggling with trying to implement the foldr() function, the function I made in the code shown below, which is a function to multiply every element in an array by 2 but it gave me an error message(shown below too), and I don't quite know how to fix it. I am open to suggestions, so any tips or fixes will greatly help. Thanks Here is the source code

multwo ::[a] -> [a]
multwo = foldr(\x acc-> (2*x):acc)[]

Here is the error message

  • No instance for (Num a) arising from a use of ‘*’
      Possible fix:
        add (Num a) to the context of
          the type signature for:
            multwo :: forall a. [a] -> [a]
    • In the first argument of ‘(:)’, namely ‘(2 * x)’
      In the expression: (2 * x) : acc
      In the first argument of ‘foldr’, namely
        ‘(\ x acc -> (2 * x) : acc)’

  |
9 | multwo = foldr(\x acc-> (2*x):acc)[]
  |                          ^^^

Your multwo function aims to multiply all elements with two, but that is only possible if this is a list of numbers. Haskell has the Num typeclass to group all number types. You thus should add a type constraint to the signature:

multwo ::  [a] -> [a]
multwo = foldr (\x acc-> (2*x) : acc) []

You can shorten the folding function further to:

\x -> (2*x :)

and further to:

(:) . (2 *)

so a shorter implementation looks like:

multwo :: Num a => [a] -> [a]
multwo = foldr () []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM