2017-10-19 50 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