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
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]
forall a. [a]
, ie 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
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 usTrue
null:: Foldable f => fa -> Bool
is a function that takes an fa
(in this case an [a]
), and returns a Bool
. It checks if a list is empty. It does not generate a list.
i would declare my list like below:
let myList = [] :: [(Integer, Integer)]
then myList
will have the type :t myList
will yield myList:: [(Integer, Integer)]
When evaluating null myList
it yields True
Every type of list is represented as []
. If you want to specify the type you can use a signature ( []:: [(a, b)]
), but often the compiler can infer the type from context:
λ> [] == [(1, 'x')]
False
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.