[Haskell-beginners] Why do i need to specify the class of a here at all?
Francesco Ariis
fa-ml at ariis.it
Wed Nov 22 21:47:13 UTC 2017
Hello Patrik,
On Wed, Nov 22, 2017 at 10:15:59PM +0100, Patrik Iselind wrote:
> My question is the following. Why do i need to add "Eq a =>" to the type
> definition of sortListOfLists?
Like you guessed, it doesn't! Just change the signature of `myOrderFunc`
to:
myOrderFunc :: [a] -> [a] -> Ordering
(Eq isn't needed, as the implementation shows).
Remember that you can arbitrarily write more restrictive signatures
than the inferred ones! It is useful to state your intent, in this
case it serves no purpose, so it's correct to get rid of the `Eq`
constraint.
> Another thought i have is if i really have to specify that i expect list of
> lists. Couldn't that be list of something else with a length, a string
> perhaps, just as well? In other words a type like sortListOfLists :: a -> a.
> As i see it that should be just as valid as the type of what i return is the
> same as that which i get as input regardless of it being a list or not.
`sortBy` signature is
sortBy :: (a -> a -> Ordering) -> [a] -> [a]
It demands a list of something (prelude Strings are lists too, specifically
`[Char]`). That "something" is dictated by myOrderFunc (`[a]`), hence
[[a]], no way around it.
Was this clear? Inferring type while writing code can be a tad difficult
at first, but then it becomes second nature
-F
More information about the Beginners
mailing list