gpt4 book ai didi

HASKELL Lambda 表达式 ‘\xs -> ...’ 有一个参数,但它的类型 ‘[t]’ 没有

转载 作者:行者123 更新时间:2023-12-05 08:17:04 25 4
gpt4 key购买 nike

我们不得不在 Haskell 中编写 lambda 函数,但它总是显示错误。我做错了什么?所有代码都有相同类型的错误,但我不明白如何使它们正确。

length' :: [a] -> [a] -> Int 
length' [] = 0
length' (x:xs) (y:ys) = \n -> if length (x:xs) > (y:ys) then 1 else if (x:xs) == (y:ys) then 0 else if (x:xs) < (y:ys) then -1

find :: a -> [a] -> Bool
find p [] = False
find p xs = \p -> if p `elem` xs then True else False

remove y [] = []
remove y (x:xs) = \xs -> if y == x then xs else x: remove y xs


• Couldn't match expected type ‘Bool’ with actual type ‘a -> Bool’
• The lambda expression ‘\ p -> ...’ has one argument,
but its type ‘Bool’ has none
In the expression: \ p -> if p `elem` xs then True else False
In an equation for ‘find’:
find p xs = \ p -> if p `elem` xs then True else False

错误是一样的

Couldn't match expected type ‘[t]’ with actual type ‘[t] -> [t]’
• The lambda expression ‘\ xs -> ...’ has one argument,
but its type ‘[t]’ has none
In the expression: \ xs -> if y == x then xs else x : remove y xs
In an equation for ‘remove’:

最佳答案

这个函数有问题:

find :: a -> [a] -> Bool
find p [] = False
find p xs = \p -> if p `elem` xs then True else False

通过它的类型声明,它接受一个 a 类型的值,一个值列表,也都是 a 类型,并返回一个 Bool

find情况下匹配pxs,编译器必须接受类型声明,所以p 必须是 a 类型,xs 必须是 [a] 类型。这意味着返回值必须Bool

然而,该表达式返回一个 lambda 表达式。该特定 lambda 表达式的类型为 Eq a => a -> Bool。您可以在 GHCi 中尝试:

Prelude> xs = undefined :: [a]
Prelude> :t \p -> if p `elem` xs then True else False
\p -> if p `elem` xs then True else False :: Eq a => a -> Bool

您可以通过返回函数来解决问题,即不返回 lambda 表达式。

关于HASKELL Lambda 表达式 ‘\xs -> ...’ 有一个参数,但它的类型 ‘[t]’ 没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59909561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com