将函数映射到字符串上

dop*_*man 2 haskell types map-function

我的理解是,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"
Run Code Online (Sandbox Code Playgroud)

当我跑这个我得到:

 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
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

Chr*_*tin 9

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"]
Run Code Online (Sandbox Code Playgroud)

对比:

Prelude> let myFunc' str = concatMap testChar str
Prelude> :t myFunc'
myFunc' :: [b] -> [b]
Prelude> myFunc' "abc"
"aabbcc"
Run Code Online (Sandbox Code Playgroud)

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

myFunc' str = concatMap testChar str
myFunc' = concatMap testChar
myFunc' str = str >>= testChar
myFunc' = (>>= testChar)
Run Code Online (Sandbox Code Playgroud)