
On Sun, Oct 03, 2010 at 08:00:19PM +0200, Klaus Gy wrote:
Hi! I have a few questions to improve my knowledge of Haskell. I didn't stumble over these problems while working on specific tasks, I more or less constructed them explicitly to get an adequate understanding of the basic Haskell semantics.
I'm fairly noobish at haskell, but I can answer some of them I think. [...]
2
Why is the following example not valid?
f :: a -> a f '0' = 0 f x = 1
I think the reason lies in the type system but I can't locate it exactly.
in the type declaration, you have claimed that f takes an object of one type and returns another object of that same type. That is, every instance of 'a' in the type declaration has to refer to the *same* type. 'a' gets bound to a specific type and must match that type throughout. now, f '0' = 0 has type f::Num t => Char -> t. This means that f takes a char and returns some numeric type. But char is not an instance of Num, and so this definition of f does not match its type signature.
3
Why is the following legal
[] :: Num a => [a]
but not with a self declared class instad of Num (unresolved overloading)?
there was a discussion here over the last few days about the polymorphism of []. It might help to read over that.
4
Why does in the declaration
f undefined = '0'
the expression undefined work apparently in the same way as a wildcard?
I believe that what you are doing here is binding the argument of f to a local name "undefined". You are subsequently not using the argument to f, so it is ignored giving a wildcard type of behavior. If this was included in a list of pattern-matching definitions of f, then it will match when all others fail. But this is not a property of "undefined" in this context. You've just given it a name that happens to coincide with a reserved word. You could just as easily use "x" or "foo" or whatever in the same way. Note that commonly, if you are not going to use the argument to a function, you use "_" to prevent it from being bound at all. for example, in: f:: Int -> Char f 1 = '1' f 2 = '2' f undefined = '0' -- using your word here, but I'd typically not since its a reserved word you could replace "undefined" with "_" f _ = '0' to get the same result. The first usage will generate a compiler warning for the unused binding. The second will not. At least that's how I understand it. A