Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare a null list with [(a,b)] Haskell

I am a bit confused on how the lists in Haskell works. I know that [] is an empty list with type [a].Is there a way to define an empty list with type [(a,b)]?

For example I know that null [1] == [] will give us True

null [(1,2)] == [] gave me the mismatched type error that's what I am assuming.

I want to know if it is possible to say something like null [(1,2)] == [(,)] will give us True

like image 242
Noopty Avatar asked Mar 20 '26 14:03

Noopty


2 Answers

I know that [] is an empty list with type [a]

Yes, but it's important to understand what “type [a]” actually means. Really it means type forall a . [a], i.e. this is not a list of elements of some particular type “a” but rather, given any choice of type a, it is a list of that type. In particular, it can also be a list of tuple type. Thus, null works just as fine with lists of tuples as with lists of any other type.

To actually see null in action on such a tuple list, you just need to supply one. For instance, null [(1,2)] uses it for a tuple-list. But in case of the empty list, there's no content of the list with which you would constrain the type. It may either be clear from the context, as in

Prelude> [null l | l <- [ [], [(1,2)], [(1,3)] ]]
[True,False,False]

or you may explicitly specify it with a signature

Prelude> null ([] :: [(String, Double)])
True
like image 126
leftaroundabout Avatar answered Mar 22 '26 04:03

leftaroundabout


Is there a way to define an empty list with type [(a,b)]?

Simply []. Indeed [] is an empty list, but the type of elements is free. It has type [a], but a can be the same as (b, c) so a 2-tuple with two different types.

For example I know that null [1] == [] will give us True

null :: Foldable f => f a -> Bool is a function that takes an f a (in this case an [a]), and returns a Bool. It checks if a list is empty. It does not generate a list.

like image 36
Willem Van Onsem Avatar answered Mar 22 '26 05:03

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!