3

我的理解是StringHaskell 中的 a 是一个演员列表Char。所以我应该能够Char -> Whatever在字符串上映射一个函数,对吧?

testChar :: Char -> String
testChar c = c:c:[]

myFunc :: String -> String
myFunc str = map testChar str

main = do
    putStrLn $ myFunc "hi"

当我运行它时,我得到:

 Couldn't match type ‘[Char]’ with ‘Char’
    Expected type: Char -> Char
      Actual type: Char -> String
    In the first argument of ‘map’, namely ‘testChar’
    In the expression: map testChar str

我在这里做错了什么?

4

2 回答 2

10

ghci是你的朋友:

Prelude> let testChar c = c:c:[]
Prelude> let myFunc str = map testChar str
Prelude> :t myFunc
myFunc :: [a] -> [[a]]
Prelude> myFunc "abc"
["aa","bb","cc"]

对比:

Prelude> let myFunc' str = concatMap testChar str
Prelude> :t myFunc'
myFunc' :: [b] -> [b]
Prelude> myFunc' "abc"
"aabbcc"

编写此函数的各种等效方法:

myFunc' str = concatMap testChar str
myFunc' = concatMap testChar
myFunc' str = str >>= testChar
myFunc' = (>>= testChar)
于 2015-07-30T18:59:29.160 回答
4
testChar :: Char -> String
testChar c = c:c:[]

myFunc :: String -> String
myFunc str = map testChar str

这两个没有意义。 testChar将 a 映射Char到不同的类型,并且您希望map映射该函数并从另一侧 获取相同的类型?myFunc实际上会返回 a [[Char]],而不是[Char]/ String

也许你的意思是concatMap

于 2015-07-30T18:50:32.603 回答