【发布时间】:2016-01-12 07:35:53
【问题描述】:
我正在尝试通过 Haskell 理解函数式编程,但在处理函数组合时遇到了很多麻烦。
其实我有这两个功能:
add:: Integer -> Integer -> Integer
add x y = x + y
sub:: Integer -> Integer -> Integer
sub x y = x - y
我希望能够创作它们。这没有任何意义好吧,但这是为了学习目的。
我的尝试:
foo:: (Integer -> Integer) -> (Integer -> Integer) -> Integer
foo = add . sub
我的理解:
Haskell 使用只有一个 args 的函数,因此我们在每个函数执行后返回一个新函数来执行。
所以第一个Integer 是参数类型,而第二个是必须添加第二个数字的生成函数的返回类型。
这将返回另一个函数 (sub),该函数将产生相同的流程(返回带有参数等的函数...)
我说的对吗?
这是我的实际错误代码:
src\Main.hs:23:7:
Couldn't match type `Integer' with `Integer -> Integer'
Expected type: Integer -> (Integer -> Integer) -> Integer
Actual type: Integer -> Integer -> Integer
In the first argument of `(.)', namely `add'
In the expression: add . sub
src\Main.hs:23:13:
Couldn't match type `Integer -> Integer' with `Integer'
Expected type: (Integer -> Integer) -> Integer
Actual type: Integer -> Integer -> Integer
Probable cause: `sub' is applied to too few arguments
In the second argument of `(.)', namely `sub'
In the expression: add . sub
我不知道我做错了什么。
您能帮我多了解一下这个错误,以便我找到解决方案吗?
【问题讨论】:
-
你是对的,它“没有任何意义”——在数学中没有组合二进制函数的概念。如果你想让它有意义,你首先需要定义什么是“组合”加减法。
-
你的 foo 类型表示加法和减法的合成是一个接受两个 函数 (
Integer -> Integer) 并返回一个整数的函数。
标签: haskell functional-programming function-composition