简体   繁体   中英

type error in func declaration

I do:

Prelude> "sone" ++ "otehr"
"soneotehr"

But such code:

addOneToElement :: [a] -> [a]
addOneToElement element = element ++ "next"

main = do
   let s = addOneToElement("some")
   putStrLn s

produces this output:

all_possible_combinations.hs:22:37:
    Couldn't match expected type `a' against inferred type `Char'
      `a' is a rigid type variable bound by
          the type signature for `addOneToElement'
            at all_possible_combinations.hs:21:20
      Expected type: [a]
      Inferred type: [Char]
    In the second argument of `(++)', namely `"next"'
    In the expression: element ++ "next"

Why I get this error and how I can fix it?

Your type signature should be:

addOneToElement :: [Char] -> [Char]

(Or more simply, addOneToElement :: String -> String )

The " a " in your type signature is a wildcard - it can match anything. However you are trying to concatenate a list of Char to a list of anything - and there is no way to do that.

Why are you using a type variable here anyway? The only type that can match is Char , since the second operand of (++) is fixed to [Char] ( "next" ).

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