使Monad类型显示

时间:2017-10-19 16:22:44

标签: haskell

我正在制作一个迷宫发生器,并希望通过打印来显示迷宫。我有一个墙类型和一个能够产生这些墙的随机迷宫的功能。

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.

我的代码中缺少什么来解决这个问题?

2 个答案:

答案 0 :(得分:1)

您希望漂亮的打印机具有类型:

prettyPrint :: WeightedWall -> String

然后,您需要从WeightedWall个实例中选择MonadRandom,将其传递给prettyPrint,然后在String中打印IO单子。

getRandomR函数是MonadRandom类型类的成员,因此它不会告诉我们您正在使用哪个MonadRandom实例。我将假设IO,因为它一石二鸟(随机来源和印刷)。您的main函数可能如下所示:

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

答案 1 :(得分: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