如何在列表中找到小于第一个数字(头)的数字?

时间:2015-11-18 17:27:47

标签: haskell functional-programming

我想定义一个找到所有数字的函数smaller 一个小于同一列表中第一个数字的列表。

例如,smaller [5, 7, 1, 2, 3]应返回[1, 2, 3]

这是我的代码:

smaller :: (Ord a) => [a] -> [a]
smaller [] = []
smaller (x:xs) = smaller [a | a <- xs, a <= x)

任何人都可以帮助/指导我吗?

2 个答案:

答案 0 :(得分:3)

嘿,你基本上已经拥有它 - 只需将最后)更改为]并删除smaller(为什么要让列表变小?)

smaller :: (Ord a) => [a] -> [a]
smaller [] = []
smaller (x:xs) = [a | a <- xs, a < x]

让这一点变得更加清晰 - 你拥有它的方式就是:

    第一步来自[1,2,3]
  • [5,7,1,2,3]
  • 然后重新应用smaller[]获取[1,2,3]
  • 再次将smaller应用于[]以获得最终[];)

如果您只想要小于x的元素,那么它应该是a < x而不是x <= a - 您的示例不清楚,但主题想要< < / p>

如果您不喜欢 list-comprehensions ,请使用filter

smaller :: (Ord a) => [a] -> [a]
smaller [] = []
smaller (x:xs) = filter (< x) xs

答案 1 :(得分:0)

Carsten的回答是正确的,但值得注意的是,使用filter函数而不是理解,这是一个更惯用的解决方案:

smaller :: Ord a => [a] -> [a]
smaller [] = []
smaller (a:as) = filter (<=a) as

练习:编写自己的filter函数版本。不要使用理解。签名:

-- | Return a list of the elements that satisfy the condition 
-- specified by the first argument, in the same order as they
-- appear in the original.
--
-- Some test cases to check whether you're doing it right:
--
-- > filter (\_ -> True) [1..10] == [1..10]
-- > filter (\_ -> False) [1..10] == []
-- > filter even [1..10] == [2,4,6,8,10]
--
filter :: (a -> Bool) -> [a] -> [a]