2

我刚刚从真实世界的 haskell 中输入了 RandomState 示例。它看起来像这样:

import System.Random
import Control.Monad.State

type RandomState a = State StdGen a

getRandom :: Random a => RandomState a
getRandom =
  get >>= \gen ->
  let (val, gen') = random gen in
  put gen' >>
  return val

getTwoRandoms :: Random a => RandomState (a, a)
getTwoRandoms = liftM2 (,) getRandom getRandom

它可以工作,但不会显示结果。我收到错误消息:

No instance for (Show (RandomState (Int, Int)))
  arising from a use of `print' at <interactive>:1:0-38
Possible fix:
  add an instance declaration for (Show (RandomState (Int, Int)))
In a stmt of a 'do' expression: print it

我在为 Show RandomState 添加实例时遇到了一些问题。谁能告诉我这是怎么做到的?

谢谢。

4

2 回答 2

3

为了明确起见,正如jberryman和对问题的评论所暗示的那样:类型的东西RandomState (a, a)是一个函数,而不是一个值。要对它做任何事情,你想以初始状态运行它

我猜你想要这样的东西:

> fmap (runState getTwoRandoms) getStdGen
((809219598,1361755735),767966517 1872071452)

这基本上就是runTwoRandomsRWH 中更进一步的功能正在做的事情。

于 2010-06-22T14:29:07.323 回答
2

由于RandomStateis 的同义词State并且没有showdefined for的实例State,因此您将无法显示它。

您也不能这样做,derive show因为State它只是一个函数的包装器,而 Haskell 无法定义一个show有用的 for 函数:

Prelude> show (+)

<interactive>:1:0:
    No instance for (Show (a -> a -> a))
      arising from a use of `show' at <interactive>:1:0-7
    Possible fix: add an instance declaration for (Show (a -> a -> a))
    In the expression: show (+)
    In the definition of `it': it = show (+)

编辑:忘了添加另一部分:GHCi 给你这个错误,因为它show在你输入的表达式的幕后使用...... REPL 和所有这些。

于 2010-06-22T14:17:30.223 回答