HASKELL lambda表达式'\ xs->…'具有一个参数,但其类型'[t]'没有任何参数

问题描述 投票:-1回答:2

我们不得不在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’:
haskell lambda lambda-calculus
2个回答
10
投票

您对此功能有疑问:

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

通过其类型声明,它接受类型为a的值,值列表以及所有类型为a的值,并返回Bool

findp匹配的xs情况下,编译器必须接受类型声明,因此p必须为a类型,并且xs必须为[ C0]。这意味着返回值必须[a]

但是,该表达式返回一个lambda表达式。该特定的lambda表达式的类型为Bool。您可以在GHCi中尝试:

Eq a => a -> Bool

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


4
投票

不幸的是,有很多错误:我只会指出第一个错误。

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

这表明length' :: [a] -> [a] -> Int 接受两个length'类型的参数并返回一个[a]。这很奇怪:为什么长度函数需要two列表?让我们假设您确实想要并继续使用两个参数。

Int

此处定义具有单个参数length' [] = 0 length'。为什么不两个?

[]

这里您定义了具有两个参数length' (x:xs) (y:ys) = \n -> ... x:xs的长度。但是,您返回的函数y:xs\n -> ...返回类型不匹配。

此外:

Int

在上面比较length (x:xs) > (y:ys) 和列表。例如,Int是真的吗?不,这是毫无意义的比较。

© www.soinside.com 2019 - 2024. All rights reserved.