2014-10-19 135 views
0

我有下面的代碼段:用實際類型未綁定變量的類型錯誤?

run :: State' s a -> s -> (a, Counts) 
run s x = do 
     put x 
     p <- runState' s 
     (1, Counts 0 0 0 0) 

當我嘗試編譯,我得到了錯誤無法比擬預期類型(A,T0)(S,計數) - >( a,s,counts)
但是,p的類型不應該受到任何限制嗎?

以下是描述國家代碼「數據類型,如果它是需要

newtype State' s a = State' { runState' :: (s, Counts) -> (a, s, Counts) } 

instance Functor (State' s) where 
    fmap = liftM 

instance Applicative (State' s) where 
    pure = return 
    (<*>) = ap 

instance Monad (State' s) where 

    -- return :: a -> State' s a 
    return x = State' f 
       where f = \(s, count) -> (x,s,count <> oneReturn) 

    -- (>>=) :: State' s a -> (a -> State' s b) -> State' s b 
    st >>= k = State' (\(s, count) -> let (x,s',count') = runState' st (s, count) in runState' (k x) (s',count' <> oneBind)) 

instance MonadState (State' s) s where 

    -- get :: State' s s 
    get = State' (\(s, count) -> (s, s, count <> oneGet)) 

    -- put :: s -> State' s() 
    put s' = State' (\(s, count) -> ((), s', count <> onePut)) 

側面說明,我也難倒以我怎麼能夠讓國家的‘數’部分」出來的狀態',所以我可以把它寫在屏幕上

也許這對解釋跑步應該做什麼更有幫助。
例如,如果您使用一個函數標籤,它使用一個狀態標籤樹中的每個節點增加數字,然後執行運行(標籤樹)30 它應該把30放在狀態,運行標籤(so它從30開始帶有標籤),然後在屏幕上打印結果樹,以及狀態的「計數」部分,該部分追蹤單次操作和獲取/放置的頻率。

+2

對元組返回類型使用'do'似乎是錯誤的。 AFAIK元組不是單子。那麼你認爲你使用「做」的monad是什麼? – Shoe 2014-10-19 16:49:17

+0

國家'monad我想。 不可能從不是monad的do塊返回某些東西嗎? – LordofTurtles 2014-10-19 17:02:22

+0

即使這樣,當返回類型是'(a,...)',其中'a'不受約束時,返回'(1,...)'是沒有意義的。 – rightfold 2014-10-19 17:03:35

回答

1

這裏的根本問題是您不恰當地使用do表示法。的do任何代碼塊必須有一個一元類型,如:

example :: String -> IO() 
example s = do { ... } 

類型IOMonad。您的do區塊的型號爲(a, Counts)。這不是一種類型。

我想你想什麼是這樣的:

run :: State' s a -> s -> (a, Counts) 
run s x = (a, c) 
    where (a, _, c) = runState' s x 

但是你寫的東西從我不是有信心,我知道在您使用它會如此不同。如果這沒有意義,請發表評論。