Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I put multiple elements into ‘elem’

Let’s say I want to do something like"ace" `elem` "abcdefg". Of course we can’t because you need a list of the first elements type. Instead is there a way we could turn this into taking every char in "ace" and comparing them individually with "abcdefg", then using or statements to combine them, but without manually doing this (because in my program it’s a variable of unknown length and characters).

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is a specific case of a more general problem: you have a function Char -> Bool (or a -> Bool) and you want to adapt it as a function [a] -> Bool. In other words, what you need is a function

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

Well, that’s actually something you can ask Hoogle about! The first hits are

any :: (a -> Bool) -> [a] -> Bool
base GHC.List GHC.OldList
Applied to a predicate and a list, any determines if any element of the list satisfies the predicate. For the result to be False, the list must be finite; True, however, results from a True value for the predicate applied to an element at a finite index of a finite or infinite list.

>>> any (> 3) []
False

>>> any (> 3) [1,2]
False

>>> any (> 3) [1,2,3,4,5]
True

>>> any (> 3) [1..]
True

>>> any (> 3) [0, -1..]
* Hangs forever *

all :: (a -> Bool) -> [a] -> Bool
base GHC.List GHC.OldList
Applied to a predicate and a list, all determines if all elements of the list satisfy the predicate. For the result to be True, the list must be finite; False, however, results from a False value for the predicate applied to an element at a finite index of a finite or infinite list.

>>> all (> 3) []
True

>>> all (> 3) [1,2]
False

>>> all (> 3) [1,2,3,4,5]
False

>>> all (> 3) [1..]
False

>>> all (> 3) [4..]
* Hangs forever *

Now you need to think which of these is right for your case, and then use it accordingly. You want

  all⁄any (\c -> c`elem`"abcdefg") "ace"

This can also be written with an infix section:

  all⁄any (`elem`"abcdefg") "ace"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading