Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two lists have the same elements

Tags:

haskell

I'm trying to write a function wich given two lists returns a boolean responding if the two lists have the same elements, even if they do not appear in the same order. I've got something like this:

function :: [a] -> [a] -> Bool
function (x:xs) y = elem x y && function xs y

The problem with this is that there's no pattern when xs is empty, and I do not have any idea how to deal with that case. Any other way to solve this will be really welcome, I am quite new to Haskell.

Thanks all!

like image 973
lluchmk Avatar asked Jun 01 '14 10:06

lluchmk


People also ask

How do you know if two lists have the same element?

Another approach to find, if two lists have common elements is to use sets. The sets have unordered collection of unique elements. So we convert the lists into sets and then create a new set by combining the given sets. If they have some common elements then the new set will not be empty.

How do you find common items between two lists?

Use the intersection function to check if both sets have any elements in common. If they have many elements in common, then print the intersection of both sets.

How can you tell if two ArrayList has the same element?

You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false.


2 Answers

This works as well

import Data.List

function :: (Eq a) => [a] -> [a] -> Bool
function x y = null (x \\ y) && null (y \\ x)
like image 162
Kaan Dedeoglu Avatar answered Sep 30 '22 15:09

Kaan Dedeoglu


Use the clause:

function [] y = True

All the elements of the empty list are in the list y.

like image 37
Dan D. Avatar answered Sep 30 '22 16:09

Dan D.