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

uly*_*ana 1 lambda haskell types arguments type-mismatch

我们不得不在 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
Run Code Online (Sandbox Code Playgroud)

错误是一样的

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’:
Run Code Online (Sandbox Code Playgroud)

Mar*_*ann 12

你有这个功能的问题:

find :: a -> [a] -> Bool
find p [] = False
find p xs = \p -> if p `elem` xs then True else False
Run Code Online (Sandbox Code Playgroud)

通过它的类型声明,它接受一个 typea的值,一个值列表,还有所有的 type a,并返回一个Bool.

findpand匹配的情况下,xs编译器必须接受类型声明,因此p必须是 type a,并且xs必须是 type [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
Run Code Online (Sandbox Code Playgroud)

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


chi*_*chi 6

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

length' :: [a] -> [a] -> Int 
Run Code Online (Sandbox Code Playgroud)

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

length' [] = 0
Run Code Online (Sandbox Code Playgroud)

在这里,您定义length'了一个参数[]。为什么不是两个?

length' (x:xs) (y:ys) = \n -> ...
Run Code Online (Sandbox Code Playgroud)

在这里,您定义具有两个参数的长度,x:xsy:xs。但是,您返回了一个\n -> ...Int返回类型不匹配的函数。

而且:

length (x:xs) > (y:ys)
Run Code Online (Sandbox Code Playgroud)

上面你比较了一个Int和一个列表。是5 < [1,2,3]真的吗?不,这是无意义的比较。