2015-06-22 18 views
0

我试图实现由点一个类型索引“DrawEnv”类型的类:如何使用GHC MultiParamTypeClass

{-# LANGUAGE FlexibleContexts #-} 
{-# LANGUAGE FlexibleInstances #-} 
{-# LANGUAGE MultiParamTypeClasses #-} 
{-# LANGUAGE TypeSynonymInstances #-} 

class Monad m => DrawEnv p m where 
    box  :: p -> p -> m() 
    clear :: m() 
    line :: p -> p -> m() 

type Pos = (Float,Float) 

instance DrawEnv Pos IO where 
    box  p0 p1 = putStrLn $ "Box " ++ show p0 ++ " " ++ show p1 
    clear   = putStrLn "Clear" 
    line p0 p1 = putStrLn $ "Line " ++ show p0 ++ " " ++ show p1 

draw :: DrawEnv Pos m => m() 
draw = do 
    clear 
    box (10.0,10.0) (100.0,100.0) 
    line (10.0,10.0) (100.0,50.0) 

但是GHC是不开心:

Could not deduce (DrawEnv (t0, t1) m) arising from a use of `box' 
from the context (DrawEnv Pos m) 
    bound by the type signature for draw :: DrawEnv Pos m => m() 
    at Code/Interfaces3.hs:63:9-29 
The type variables `t0', `t1' are ambiguous 
Relevant bindings include 
    draw :: m() (bound at Code/Interfaces3.hs:64:1) 
Note: there is a potential instance available: 
    instance DrawEnv Pos IO -- Defined at Code/Interfaces3.hs:56:10 
In a stmt of a 'do' block: box (10.0, 10.0) (100.0, 100.0) 
In the expression: 
    do { clear; 
     box (10.0, 10.0) (100.0, 100.0); 
     line (10.0, 10.0) (100.0, 50.0) } 
In an equation for `draw': 
    draw 
     = do { clear; 
      box (10.0, 10.0) (100.0, 100.0); 
      line (10.0, 10.0) (100.0, 50.0) } 

我的问题是,为什么考虑到Pos限制,GHC不接受这个问题?

+1

我没有GHC 7.8和7.10的任何错误。 –

回答

2

该类定义将不起作用,因为clear的类型没有提及类型变量p,所以不可能使用具体类型实例化clear。向boxline添加类型签名将无济于事 - 即使clear :: IO()也会产生类型错误。

这可能是固定的,加入的功能依赖于你的类:

class Monad m => DrawEnv p m | m -> p where 

那么你的代码的其余部分进行编译。或者,你可以将你的班级分为两类:

class Monad m => MonadDraw m where 
    putStringLn :: String -> m() 

    clear :: m() 
    clear = putStringLn "Clear" 

class DrawEnv p where 
    box  :: MonadDraw m => p -> p -> m() 
    line :: MonadDraw m => p -> p -> m() 

instance (Fractional a, Show a, Fractional b, Show b) => DrawEnv (a,b) where 
    box  p0 p1 = putStringLn $ "Box " ++ show p0 ++ " " ++ show p1 
    line p0 p1 = putStringLn $ "Line " ++ show p0 ++ " " ++ show p1 

draw :: MonadDraw m => m() 
draw = do 
    clear 
    box (10.0,10.0) (100.0,100.0) 
    line (10.0,10.0) (100.0,50.0) 
+0

使用函数依赖是一个很好的解决方案。谢谢! – mbrodersen

2

该代码不明确。具体而言,我们不知道(10.0,10.0)的类型。例如,它可能是(Double,Double)。这是最普遍的类型是(Fractional a,Fractional b) => (a,b)

的解决方案是写

box ((10.0,10.0) :: Pos) ((100.0,100.0)::Pos) 

代替并且类似地固定其它线路。