我对Haskell和functionall编程很陌生,有点困惑。为什么我不能建立一个匿名函数,或者它甚至是可能的?
我有以下代码:
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当我试图写成这样:
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])然后得到以下错误,如果我试图将其加载到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.发布于 2016-12-08 14:29:46
密码
| otherwise = head (myFilter (f x) [x-1, x-2..1])
where f x y= x `mod` y == 0等于
| otherwise = head (myFilter (f x) [x-1, x-2..1])
where f = \x y -> x `mod` y == 0这相当于
| otherwise = head (myFilter ((\x y -> x `mod` y == 0) x) [x-1, x-2..1])
-- ^^^请注意,x的应用程序仍然存在!我们可以通过应用匿名函数( beta步骤)进一步简化:
| otherwise = head (myFilter (\y -> x `mod` y == 0) [x-1, x-2..1])发布于 2016-12-08 14:22:06
x是largestDivisible的一个参数,但不需要将它作为参数传递给lambda。lambda可以从捕获的上下文中获取x,并且只需要y作为参数。
第一个版本将部分应用的f x传递给myFilter,在给出第一个参数的情况下,该函数是一个一元函数。
第二个版本尝试传递两个参数的lambda,而不首先使用部分应用程序获得合适的函数。
或者像第一个示例那样使用部分应用程序,或者只编写一个参数的lambda (y)。
https://stackoverflow.com/questions/41041583
复制相似问题