【问题标题】:Recursive syntax in haskell using andhaskell中的递归语法使用and
【发布时间】:2021-04-19 09:12:59
【问题描述】:

我正在尝试创建一个递归函数,该函数接受并输入 List 的列表,如下所示:[[1,2], [4], [3], [1]] 并返回一个 Bool。它应该检查所有列表是否至少包含一个唯一编号。我正在尝试使用下面的两个函数递归地执行此操作。

从第二个列表中的第一个列表中删除所有元素的函数:

helper :: Eq a => [a] -> [a] -> [a]
helper a b = filter (`notElem` b) a

主要功能:

function :: [[Int]] -> Bool 
function [] = True
function (x:y:xs) = (not (null r)) and (function (r ++ xs))
    where r = helper(x,y)

但是,我从编译器中得到了这两个错误:

Couldn't match expected type ‘(t0 Bool -> Bool) -> Bool -> Bool’
              with actual type ‘Bool’

The function ‘not’ is applied to three arguments,
  but its type ‘Bool -> Bool’ has only one
  In the expression: (not (null r)) and (function (r ++ xs))
  In an equation for ‘function’:
      function (x : y : xs)
        = (not (null r)) and (function (r ++ xs))
        where
            r = helper (x, y)

我是 Haskell 新手,对 Haskell 语法不太熟悉。

【问题讨论】:

  • and 不是你想的那样,你在找&&
  • 一个猜测:您尝试检查第二个列表是否包含任何不在第一个列表中的元素,第三个应该包含一个不在第一个或第二个中的元素,...?
  • helper(x,y) 是错误的,因为helper 没有将一对作为参数。请改用helper x y

标签: haskell


【解决方案1】:

第一个问题 - 调用具有多个参数的函数。这是通过以下语法完成的:myFunction a b(不是myFunction (a, b))。

原因是(a, b) 是一个元组。 Here's a link with some info on tuples

第二个问题 - 您使用的是 and 而不是 &&

第三个问题 - 您试图将 rxs++ 组合,但 r 的类型是 [Int]xs 的类型是 [[Int]]。如果您的目标是将r 添加到xs,那么您可以使用: 来完成此操作

helper :: Eq a => [a] -> [a] -> [a]
helper a b = filter (`notElem` b) a

function :: [[Int]] -> Bool 
function [] = True
function (x:y:xs) = not (null r) && function (r : xs)
    where r = helper x y

【讨论】:

    猜你喜欢
    • 2018-03-25
    • 2011-02-16
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多