How to check if some items are in the list?

I am trying to confuse the attempt to haskell ' Scala One Liners equivalent that recently appeared on Reddit / Hacker News.

Here is what I have so far (people could make them much better than me, but these are my beginner level attempts)

https://gist.github.com/1005383

The one I'm stuck on checks to see if the items are in the list. Basically an example of Scala is

val wordlist = List("scala", "akka", "play framework", "sbt", "typesafe") val tweet = "This is an example tweet talking about scala and sbt." (words.foldLeft(false)( _ || tweet.contains(_) )) 

I'm a little dumb how to do this in Haskell. I know what you can do:

 any (=="haskell") $ words "haskell is great!" 

To check if one word is present, but the Scala example asks if any of the words are in the word list in the test line.

I can not find the contains function or something like this. I know that you could probably write a function for this, but that defeats the execution point of this task on one line.

Any help would be appreciated.

+6
source share
3 answers

You can use the elem function from Prelude, which checks if an item is in the list. It is usually used in the form of infix:

 Prelude> "foo" `elem` ["foo", "bar", "baz"] True 

Then you can use it in the operator section just as you did with == :

 Prelude> let wordList = ["scala", "akka", "play framework", "sbt", "types"] Prelude> let tweet = "This is an example tweet talking about scala and sbt." Prelude> any (`elem` wordList) $ words tweet True 

If you need a function, but you don’t know its name, try using Hoogle to search for a function by type.

Here you need something that checks if an item of any type is in the list of things of the same type, that is, something like type a -> [a] -> Bool (you also need an Eq constraint, but let's say you didn’t. I don’t know. Putting this type signature in Hoogle gives elem as the best result .

+11
source

How about using Data.List.intersect ?

 import Data.List.intersect not $ null $ intersect (words tweet) wordList 
+6
source

Although there are already good answers, I thought it would be nice to write something in the spirit of your source code using any . This way, you can see how to compose your own complex queries from simple reusable parts, rather than using ready-made parts like intersect and elem :

 any (\x -> any (\y -> (y == x)) $ words "haskell is great!") ["scala", "is", "tolerable"] 

With a little reordering, you can read it in English: is there a word x in the sentence that the list contains y , so x == y ? It is clear how to extend to more "axes" than two, to make comparisons other than == , and even mix them with all .

+3
source

Source: https://habr.com/ru/post/889677/


All Articles