Sunday 5 June 2016

Haskell: Get all occurrences of a number in list

Following statement return all the occurrence os given number in the list.

getOccurrences num list = [x | x <- list, (x == num)]


Prelude> let getOccurrences num list = [x | x <- list, (x == num)]
Prelude> 
Prelude> getOccurrences 1 [1, 2, 3, 4, 1, 3, 1, 2]
[1,1,1]
Prelude> 
Prelude> getOccurrences 1 [1]
[1]
Prelude> 
Prelude> getOccurrences 1 [3, 5, 7]
[]
Prelude> 
Prelude> getOccurrences 1 [3, 5, 7, 1]
[1]


Previous                                                 Next                                                 Home

No comments:

Post a Comment