3

私の理解ではString、Haskell の 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

この二つは意味がありません。 testCharaを別の型にマップし、その関数をマップして反対側から 同じChar型を取得することを期待していますか? 実際には/ではなく を返します。mapmyFunc[[Char]][Char]String

おそらくあなたは意味しましたconcatMapか?

于 2015-07-30T18:50:32.603 に答える