首页 > 解决方案 > Haskell 函数,它接受一个元素列表,如果列表包含重复项,则返回 true,否则返回

问题描述

我正在尝试创建一个 haskell 函数,该函数采用元素列表,如果列表包含重复项,则返回 true,否则返回 false。

这就是我所拥有的...我收到具有不同数量参数的重复项的错误

duplicates :: Eq a => [a] -> Bool
duplicates _ []= False
duplicates (x:xs) = callback n xs
where callback  = if x == n then elem else duplicates

duplicatesTests = [
                 not $ duplicates [1..10]
                ,duplicates "ABCAD"
                ,not $ duplicates "BAD"
                ,duplicates [1,2,1]
              ]

标签: haskell

解决方案


肯定是

duplicates :: Eq a => [a] -> Bool
duplicates [] = False
duplicates (x:xs) = callback n xs
    where        -- callback       = if x == n then elem else duplicates
                    callback n xs  = if x == n then elem else duplicates

n必须作为callback' 参数出现才能在callback' 正文中引用它。

不过,在调用callbackn超出了范围。换句话说,它没有在任何地方定义。

通常,您使用的任何名称都必须来自某个地方


推荐阅读