我定义了以下模块:
module ComplexCompose where
isEven x =
if x `rem` 2 == 0 then
(True, "Is Even")
else
(False, "Is Odd")
negateIt x = ( not x, "negated")
composer x =
(c, b ++ ", " ++ d) where (a,b) = isEven x
(c,d) = negateIt a
以下对composer的修改有效:
composerV1 x f g =
(c, b ++ ", " ++ d) where (a,b) = f x
(c,d) = g a
我希望让composer函数返回一个将f和g组合起来的lambda函数。我尝试过以下方法:
composerV2 f g =
\x -> (c, b ++ ", " ++ d) where (a,b) = f x
(c,d) = g a
它不能工作。这个版本有什么问题?
编译器输出:
• Couldn't match expected type ‘t0 -> (t5, t4)’
with actual type ‘t3’
because type variables ‘t4’, ‘t5’ would escape their scope
These (rigid, skolem) type variables are bound by
the inferred type of
a :: t5
b :: t4
at complex-compose.hs:27:34-44
• In the expression: f x
In a pattern binding: (a, b) = f x
In an equation for ‘c4’:
c4 f g
= \ x -> (c, b ++ ", " ++ d)
where
(a, b) = f x
(c, d) = g a
• Relevant bindings include
a :: t5 (bound at complex-compose.hs:27:35)
b :: t4 (bound at complex-compose.hs:27:37)
f :: t3 (bound at complex-compose.hs:26:4)
c4 :: t3 -> (t2 -> (t1, [Char])) -> t -> (t1, [Char])
(bound at complex-compose.hs:26:1)
顺便说一下,以下简单的函数可以使用:
fn f g = \x = g(f x)
foo = (\x -> x+v1, \x -> x++v2) where v1 = 3*x; v2 = "hello, " ++ x
。在那个where
子句中,哪个x
(如果有的话)应该在作用域内?它应该具有什么类型?(为了回答这个问题,即使你将所有数字文字都设为Integer
,我们也不会遇到任何 Haskell 的Num
层次结构的奇怪情况,因此问题中的有趣信息仍然存在。) - Daniel Wagner