通过搜索列表 [英] Searching through list
本文介绍了通过搜索列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在试图定义一个函数,给出一个整数列表一个整数n,返回一个布尔值指示n是否在列表中恰好发生一次。
我有这一点,但它不工作,我无法弄清楚
一旦:: [A] - > (一 - >布尔) - GT;布尔
过滤器_ [] = []
过滤器P(X:XS)
| P X [= X:过滤器p XS
|否则=过滤器p XS什么,我想会是一个例子:
主营>一旦[2,3,2,4] 2
假
主营>一旦[1..100] 2
真正
解决方案
::一次(公式一)=> [一个] - GT;一个 - >布尔
一旦XS X =(== 1)$ $长度过滤器(== X)XS
I've been trying to define a function which, given a list of Integers and an Integer n, returns a Boolean indicating whether n occurs exactly once in the list.
I have this, but it is not working and I cannot figure it out
once :: [a] -> (a -> Bool) -> Bool
filter _ [] = []
filter p (x:xs)
| p x = x : filter p xs
| otherwise = filter p xs
An example of what I want would be:
Main> once [2,3,2,4] 2
False
Main> once [1..100] 2
True
解决方案
once :: (Eq a) => [a] -> a -> Bool
once xs x = (== 1) $ length $ filter (== x) xs
这篇关于通过搜索列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文