Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i use haskell to check if a list contains the values in a tuple

Tags:

haskell

I am writing some functions for graphs in Haskell, and I want to check if a list of integers, such as

[1,4, 5, 7]

contains vertices that make an edge, which i have represented as a tuple, like so

(1,5)

Im trying to take a function that takes the list and the tuple, and in this case would return true, because the list contains a 1 and a 5. The main issue i am having is that im really not sure how to search a list in Haskell. Is their a function that takes a list of type [a] and a value of type a, and returns a Bool, depending on whether [a] contains a?

like image 284
Ben313 Avatar asked Mar 08 '12 20:03

Ben313


People also ask

How do you check if a list contains an element in Haskell?

elem :: element -> list -> Bool. Use elem if you want to check whether a given element exists within a list.

How do I see if a list has duplicates in Haskell?

if it is just about knowing if the list contains duplicates you can use the nub function in Data. List like so: hasDup l = nub l == l (nub removes all duplicates... so this will be true only if there are no duplicates in the list.)

How do you check a value in Haskell?

If you need to figure out what the type of an object is in a Haskell program, I hope this is helpful. Note that if you are in GHCI, you can just put :type before your expression to determine the expression's type, or use :set +t to see the type of every expression in GHCI.

What does list do in Haskell?

In Haskell list is used to store the elements, and these elements are homogenous in nature which simply means only one type. Inside the list, we can store the list of elements that are of the same type. we can store any data type inside the list.


2 Answers

There is a function to check whether a value is in a list,

elem :: Eq a => a -> [a] -> Bool

Using that, your function is easily defined.

containsEdge :: [Int] -> (Int,Int) -> Bool
xs `containsEdge` (a,b) = (a `elem` xs) && (b `elem` xs)
like image 141
Daniel Fischer Avatar answered Oct 24 '22 06:10

Daniel Fischer


The elem function does that :

elem 1 [1,3,4]

will give True. Though this function is often used as an infix operator by surrounding it with backticks :

1 `elem` [1,4,5,7]

On the other hand, for big sets, that is not a very good idea (O(n) complexity), and you should use Set (or even IntSet if your elements are integers) instead of lists.

like image 24
Jedai Avatar answered Oct 24 '22 07:10

Jedai