我尝试实现一个基本的 lambda 函数,但遇到了一些错误,并且在此处的问题之间搜索后无法找出解决方案。我的代码是:
myMap :: (a -> b) -> [a] -> [b]
myMap addSomething [] = []
myMap addSomething (x:xs) = addSomething x : myMap addSomething xs
-- instance Show (a -> b) where
-- show a = "funcion"
list = [0..4]
listTwo = [(5 :: Int)..9]
addSomething :: Int -> Int
addSomething x = x + 1
addSomethingTwo :: Num a => a -> a-> a
addSomethingTwo x = (\x->x+1)
main = do
print $ myMap addSomething list
print $ myMap addSomethingTwo listTwo
Run Code Online (Sandbox Code Playgroud)
这是我收到的错误消息
No instance for (Show (Int -> Int)) arising from a use of `print'
Possible fix: add an instance declaration for (Show (Int -> Int))
In the expression: print
In a stmt of a 'do' block: print $ myMap addSomethingTwo listTwo
In the expression:
do { print $ myMap addSomething list;
print $ myMap addSomethingTwo listTwo }
Run Code Online (Sandbox Code Playgroud)
如果我取消注释这些行
instance Show (a -> b) where
show a = "function"
Run Code Online (Sandbox Code Playgroud)
我得到了这个奇怪的结果
[1,2,3,4,5]
[function,function,function,function,function]
[Finished in 0.4s]
Run Code Online (Sandbox Code Playgroud)
提前谢谢你,塔马斯
addSomethingTwo 结果有一个函数 (Int -> Int),而不是 Int
您需要将函数定义为
addSomethingTwo x = (\x->x+1) x
Run Code Online (Sandbox Code Playgroud)
或者,要清除 lambda 和函数参数中的 x 是不同的变量(它们在不同的范围内):
addSomethingTwo y = (\x->x+1) y
Run Code Online (Sandbox Code Playgroud)