【发布时间】:2017-05-01 11:02:59
【问题描述】:
我编写了一个函数count :: Char -> String -> Int,它计算Char 在String 中出现的次数。代码示例:
module Main where
import Data.List
main :: IO ()
main = do
print $ count 'a' "abcaaba"
count :: Char -> String -> Int
count = length . elemIndices
我得到的编译错误是
* Couldn't match type `Int' with `String -> Int'
Expected type: Char -> String -> Int
Actual type: Char -> Int
* Possible cause: `(.)' is applied to too many arguments
In the expression: length . elemIndices
In an equation for `count': count = length . elemIndices
好的,我可以写count x y = length $ elemIndices x y,这很有效。但我认为我们有
(1)(.) :: (b -> c) -> (a -> b) -> a -> c
(2)elemIndices :: Eq a => a -> [a] -> [Int] 和
(3)length :: [a] -> Int
如果count 是 (2) 和 (3) 的组合,那么在 (1) 中我们显然需要 a = Char -> [Char] 和 c = Int。如果b = [Int] 我们得到
(1') (.) :: ([Int] -> Int) -> (Char -> [Char] -> [Int]) -> Char -> [Char] -> Int
这意味着我可以编写 (2) 和 (3) 来获得 Char -> [Char] -> Int。
问题:
- 为什么我写的作文编译失败?
- 我的推理哪里出了问题?
【问题讨论】:
-
在许多 Haskell 书籍和教程中,字里行间提到的一些 Haskell 基础知识有时会被跳过或忽略。 This 文章值得一看。
标签: haskell function-composition