簡體   English   中英

如何使用GHC MultiParamTypeClass

[英]How to use GHC MultiParamTypeClass

我正在嘗試實現由點類型索引的“ DrawEnv”類型類:

{-# 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為什么不接受這一點?

代碼不明確。 具體來說,我們不知道(10.0,10.0)的類型。 例如,它可以是(Double,Double) 最一般的類型是(Fractional a,Fractional b) => (a,b)

解決的辦法是寫

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

而是類似地修復其他行。

該類定義將不起作用,因為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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM