Spa*_*kay 1 haskell functional-programming currying
我是Haskell的新手和函数编程,我有点困惑.为什么我不能讨论匿名函数,或者甚至可能?
我有以下代码:
largestDivisible :: (Integral a) => a -> a
largestDivisible x
| x <= 0 = error "NOT A VALID VALUE"
| otherwise = head (myFilter (f x) [x-1, x-2..1])
where f x y= x `mod` y == 0
Run Code Online (Sandbox Code Playgroud)
当我尝试这样写时:
largestDivisible :: (Integral a) => a -> a
largestDivisible x
| x <= 0 = error "NOT A VALID VALUE"
| otherwise = head (myFilter (\ x y = x `mod` y == 0) [x-1, x-2..1])
Run Code Online (Sandbox Code Playgroud)
然后,如果我尝试将其加载到GHCi中,我会收到以下错误,我收到以下错误:
ListStuff.hs:85:35: error:
• Couldn't match expected type ‘Bool’ with actual type ‘a -> Bool’
• The lambda expression ‘\ x y -> (mod x y == 0)’
has two arguments,
but its type ‘a -> Bool’ has only one
In the first argument of ‘myFilter’, namely
‘(\ x y -> (mod x y == 0))’
In the first argument of ‘head’, namely
‘(myFilter (\ x y -> (mod x y == 0)) [x - 1, x - 2 .. 1])’
• Relevant bindings include
x :: a (bound at ListStuff.hs:83:19)
largestDivisible' :: a -> a (bound at ListStuff.hs:83:1)
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)
x是一个参数largestDivisible,但你不需要将它作为参数传递给你的lambda.lambda可以x从捕获的上下文中获取,并且只需要y作为参数.
第一版本传递部分应用f x 到myFilter,以及-与给定的第一个参数-是一元函数.
第二个版本尝试传递两个参数的lambda,而不使用部分应用程序来首先获得合适的函数.
要么像第一个例子中那样使用部分应用程序,要么只写一个参数的lambda(y).
代码
| otherwise = head (myFilter (f x) [x-1, x-2..1])
where f x y= x `mod` y == 0
Run Code Online (Sandbox Code Playgroud)
相当于
| otherwise = head (myFilter (f x) [x-1, x-2..1])
where f = \x y -> x `mod` y == 0
Run Code Online (Sandbox Code Playgroud)
这相当于
| otherwise = head (myFilter ((\x y -> x `mod` y == 0) x) [x-1, x-2..1])
-- ^^^
Run Code Online (Sandbox Code Playgroud)
请注意,应用x仍然存在!我们可以通过应用匿名函数(beta步骤)进一步简化:
| otherwise = head (myFilter (\y -> x `mod` y == 0) [x-1, x-2..1])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
154 次 |
| 最近记录: |