I have the following functions:
which (x:xs) = worker x xs
worker x [] = x
worker x (y:ys)
| x > y = worker y ys
| otherwise = worker x ys
and am wondering how I should define the types signatures of these above functions which and worker?
For Example, which of the following ways would be best as a type signature for worker?
worker :: Num a => a -> [a] -> a,
or
worker :: Ord a => a -> [a] -> a?
I’m just really confused and don’t get which these three I should choose. I’d appreciate your thoughts. Thanks.
If you define the function without an explicit type signature, Haskell will infer the most general one. If you’re unsure, this is the easiest way to figure out how your definition will be read; you can then copy it into your source code. A common mistake is incorrectly typing a function and then getting a confusing type error somewhere else.
Anyway, you can get info on the
Numclass by typing:i Numinto ghci, or by reading the documentation. TheNumclass gives you+,*,-,negate,abs,signum,fromInteger, as well as every function ofEqandShow. Notice that<and>aren’t there! Requiring values ofNumand attempting to compare them will in fact produce a type error — not every kind of number can be compared.So it should be
Ord a => ..., asNum a => ...would produce a type error if you tried it.