2017-10-19 48 views
0

我製作迷宮發生器並希望通過打印形象化迷宮。我有一個牆型和一個隨機生成這些牆的迷宮的功能。製作Monad類型可顯示

import qualified Data.Graph.Inductive as Graph 
import   Data.Graph.Inductive (Gr, prettyPrint) 
data WeightedWall = WeightedWall (Int, Int, Int) Orientation deriving (Eq) 
weightedGrid :: MonadRandom m => Int -> Int -> Gr() (m WeightedWall) 

然而,當我打電話prettyPrint(weightedGrid 10 10),我得到這個錯誤:

Ambiguous type variable ‘m0’ arising from a use of ‘prettyPrint’ 
    prevents the constraint ‘(Show 
           (m0 WeightedWall))’ from being solved. 
    Probable fix: use a type annotation to specify what ‘m0’ should be. 

什麼我在我的代碼所缺少解決這一問題?

+3

'MonadRandom'你想'什麼M'是? – 4castle

+0

我是Haskell的新手,我不確定它應該是什麼。 weightedGrid中注入隨機性的函數是Control.Monad.Random中的getRandomR(如果有幫助)。 – chronologos

+0

'm'的一些可能的值是['Rand'](http://hackage.haskell.org/package/MonadRandom-0.5.1/docs/Control-Monad-Trans-Random-Lazy.html#t:蘭特)或'IO'。編譯器不知道要使用哪一個,除非你給'weightedGrid'調用的結果賦予一個類型註釋。 – 4castle

回答

1

你會希望你漂亮的打印機具有類型:

prettyPrint :: WeightedWall -> String 

然後,你需要從MonadRandom實例扯動WeightedWall,把它傳遞給prettyPrint,然後打印StringIO單子。

getRandomR函數是MonadRandom類型類的成員,所以它不會告訴我們您正在使用哪個實例。我將假設IO,因爲它一石二鳥(隨機源和打印)殺死。你main功能可以看看如下:

main :: IO() 
main = do 
    ww <- weightedGrid 10 10 -- pluck weighted wall from MonadRandom instance IO 
    putStrLn $ prettyPrint ww 
0

我落得這樣做:

pp :: WeightedWall -> String 
pp (WeightedWall (a, b, c) _) = show a ++ " " ++ show b ++ " " ++ show c 

main :: IO() 
main = do 
    ww <- mapM Data.Graph.Inductive.edgeLabel $ labEdges (weightedGrid 10 10) 
    forM_ (map pp ww) putStrLn