Searching through list

后端 未结 4 845
日久生厌
日久生厌 2021-01-26 14:47

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 t

4条回答
  •  感情败类
    2021-01-26 15:24

    Well, you can filter the list, then see how many elements are in the resulting filter, right?

    To get you started:

     > filter (== 2) [1,2,3,4,5]
     [2]
    
     > filter (== 2) [1,2,3,4,5,2,2]
     [2,2,2]
    

    And to fold your list down to a Bool value, here, an example where we test if a list has three elements, returning a Bool:

     > isThree (a:b:c:[]) = True
     > isThree _          = False 
    

    So it is just a short matter of composing such functions:

     > isThree . filter (==2)
    

    or your variant (e.g. matching for lists of length 1).

提交回复
热议问题