Haskell type system nuances

前端 未结 3 1610
后悔当初
后悔当初 2021-02-13 20:13

I\'ve been getting into the nitty gritty of the haskell typesystem and trying to get at the fine points of type classes. I\'ve learned a heap, but I\'m hitting a wall on the fol

3条回答
  •  甜味超标
    2021-02-13 20:24

    In

    g :: C a => a -> Int -> a
    g x y = f y
    

    the return type of f y is fixed by the type signature, so that if you call, e.g. g 'a' 3, instance C Char will be used. But in

    g :: C a => a -> Int -> String
    g x y = show(f y)
    

    there are two constraints on return type of f: it must be an instance of C (so that f can be used) and of Show (so that show can be used). And that's all! Coincidence of type variable names a in definitions of f and g doesn't mean anything. So the compiler has no way to choose between instance C Char and instance C Integer (or any instances defined in other modules, so removing these instances won't make the program compile).

提交回复
热议问题