Removing items from a list if a predicate holds

断了今生、忘了曾经 提交于 2020-01-03 05:02:08

问题


I am trying to make a function which takes as input a predicate and a list. and removes all elements from the list for which the predicate holds. What I have so far is the following function:

removeif :: func->[a]->[a]
removeif [] = []
removeif func (h:t)= if func then delete h (h:t) else removeif func t

I am confused about the func part of the func->[a]->[a] because I don't know how should I tell that its a predicate.

For example what I want is that I give from the terminal this command

removeif threefolds [1,2,3,4,5,6,7,8,9]

threefolds is a local function I have and it returns an infinite list with multiples of three and I want to remove those multiples from the input list. I am thinking of making threefold a bool function but not sure if that is necessary.


回答1:


A predicate should be a function of type a -> Bool. Therefore, the signature of removeif should be

removeif :: (a -> Bool) -> [a] -> [a]

If threefolds has type a -> Bool, you'll be fine :-)




回答2:


Threefolds should return a boolean, something like this:

   let threefolds x =  x `mod` 3 == 0


来源:https://stackoverflow.com/questions/34785585/removing-items-from-a-list-if-a-predicate-holds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!