Understanding the Haskell Filter

I understand that the Haskell filter is a high-order function (which means a function that takes another function as a parameter) that goes through a list that checks which element fulfills a certain Boolean condition.

I do not quite understand its definition:

filter:: (a->Bool)->[a]->[a]
filter p [] = []
filter p (x:y) | p x = x:filter p y
               | otherwise = filter p y

I understand that if I pass an empty list of functions, it will simply return an empty list, but how do I read the last two lines?

+5
source share
2 answers

It uses guards , which, if you come from a language with C-style syntax, are a bit like a structure switch.

: p true x, . .

:

filter p (x:y) = if (  p x ) then
                     x:filter p y
                 else
                     filter p y
+11

filter :

filter, , , ; .,

filter p xs = [x | x <- xs, p x]

-, , , filter :

  • ( ), , , ,
  • , , ,
  • .

.

, , :

filter _ []      = []
filter p (x:xs)
  | p x          = x : filter p xs
  | otherwise    =     filter p xs

, , .

(x:y), (x:xs) -think: "ex exes" - , ( a) ( [a], .. a).

, filter , x.

+7

All Articles