在Haskell中绘制随机漫步

时间:2018-08-18 21:26:16

标签: haskell

我正在尝试在Haskell中绘制随机游走路线。 我使用getStdGen随机数。 我正在使用Chart.Easy进行绘图。 我在haskell上大吃一惊,我无法理解我得到的编译器错误。

import Graphics.Rendering.Chart.Easy
import Graphics.Rendering.Chart.Backend.Cairo
import System.Random

main = toFile def "random_walk.png" $ do
 layout_title .= "Random Walk"
 setColors [opaque blue, opaque red]
 g <- getStdGen
 plot (line "random walk" [ take 100 $ walk (0,0) ( randoms g :: [Float])])

walk :: (Float, Float) -> [Float] -> [(Float, Float)]
walk (x,y) (dx:dy:list) = (x+dx,y+dy):(walk (x+dx,y+dy) list)

错误是:

[1 of 1] Compiling Main             ( simple.hs, interpreted )

simple.hs:8:7: error:
    * Couldn't match type `IO'
                     with `Control.Monad.Trans.State.Lazy.StateT
                             (Layout Float Float) (Control.Monad.Trans.State.Lazy.State CState)'
      Expected type: Control.Monad.Trans.State.Lazy.StateT
                       (Layout Float Float)
                       (Control.Monad.Trans.State.Lazy.State CState)
                       StdGen
        Actual type: IO StdGen
    * In a stmt of a 'do' block: g <- getStdGen
      In the second argument of `($)', namely
        `do layout_title .= "Random Walk"
            setColors [opaque blue, opaque red]
            g <- getStdGen
            plot
              (line
                 "random walk" [take 100 $ walk (0, 0) (randoms g :: [Float])])'
      In the expression:
        toFile def "random_walk.png"
          $ do layout_title .= "Random Walk"
               setColors [opaque blue, opaque red]
               g <- getStdGen
               plot
                 (line
                    "random walk" [take 100 $ walk (0, 0) (randoms g :: [Float])])
  |
8 |  g <- getStdGen
  |       ^^^^^^^^^
Failed, no modules loaded.

有人知道吗?谁能帮我?还有其他评论吗?

修复代码后,重新设置为 this image.

1 个答案:

答案 0 :(得分:3)

问题在于toFile的第三个参数是特殊EC单子中的一个动作。此monad无法执行IO,因此您不能在其do-block中包含诸如getStdGen之类的IO操作。

相反,使用单独的外部IO do-block来获取所需的随机数流作为纯值,然后可以在内部EC do-block中自由使用它,如下所示:

main :: IO ()
main = do
  -- this is do-block for the IO monad
  nums <- randomRs (-1,1) <$> getStdGen
  toFile def "random_walk.png" $ do
    -- this is the do-block for the EC monad
    layout_title .= "Random Walk"
    setColors [opaque blue, opaque red]
    plot (line "random walk" [ take 100 $ walk (0,0) nums ])

walk :: (Float, Float) -> [Float] -> [(Float, Float)]
walk (x,y) (dx:dy:list) = (x+dx,y+dy):(walk (x+dx,y+dy) list)