Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I write a general function to check if two lists are equal?

Tags:

haskell

I am learning Haskell and I don't understand why I can do this:

f :: [Int] -> Bool
f l  
    | l==l = True
    | otherwise = False

But I can't do this.

f :: [a] -> Bool
f l  
    | l==l = True
    | otherwise = False

What's going on under the hood?

like image 746
pt2121 Avatar asked Dec 25 '11 06:12

pt2121


People also ask

How do you check if two lists are equal?

equals() method. A simple solution to compare two lists of primitive types for equality is using the List. equals() method. It returns true if both lists have the same size, and all corresponding pairs of elements in both lists are equal.

How can I check if two lists are the same in C#?

Equals(Object) Method which is inherited from the Object class is used to check if a specified List<T> object is equal to another List<T> object or not. Syntax: public virtual bool Equals (object obj);


1 Answers

Given two values of an arbitrary type, Haskell does not necessarily know how to compare them for equality. == is only defined for types that are part of the Eq class.

For example, determining if two functions are equal is undecidable in general (I think).

You can compare two lists by checking if each element is equal to its corresponding element in the other list. However, this only makes sense if you can compare the elements for equality, so you have to add a constraint:

f :: Eq a => [a] -> Bool
like image 184
Tikhon Jelvis Avatar answered Sep 21 '22 13:09

Tikhon Jelvis