2010-06-22 85 views
2

我刚刚从真实世界的haskell中输入了RandomState示例。它看起来像这样:将一个Show实例添加到RWH的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添加实例时遇到了一些麻烦。任何人都可以告诉我这是怎么完成的?

谢谢。

+1

要诊断这一点,我们需要您用来尝试打印的代码。我猜你忘了runState? – 2010-06-22 06:18:00

+0

我没有写任何额外的代码打印,我只是跑了:getTwoRandoms ::(RandomState(Int,Int)) 但是RandomState不知道如何显示它自己。听起来像我没有忘记runState。 – Kurt 2010-06-22 08:02:36

+0

也许你想要'runTwoRandoms'代替下面的一个部分? – kennytm 2010-06-22 11:47:29

回答

3

对于被明确起见,作为jberryman关于这个问题的评论暗示:东西RandomState (a, a)型的是一个函数,而不是一个值。要做任何事情,你想运行它与初始状态

我猜你想是这样的:

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

这基本上是什么runTwoRandoms功能位进一步RWH在做什么。

+0

我将不得不再次阅读那一章。我真的认为我已经开始明白了。 – Kurt 2010-06-22 14:54:29

+1

@Kurt:它是否让你绊倒了“隐藏”功能?有点令人困惑的是,尽管它实际上是's - >(a,s)'类型的函数,你可以在'do'块中处理'State s a'类型的类型'a'的值。通过“State”的重新实现似乎可以帮助一些人更好地感受它的工作方式和原因 - 我在[我以前的答案之一]中做到了这一点(http://stackoverflow.com/questions/1956518/1957379 #1957379),我也看过一篇博文或两篇文章。 – 2010-06-22 15:05:58

+0

@Kurt:国家monad很奇怪。以这种方式考虑一下:所有的monadic机器('>> =','return'等)都是在'State'包装器中组成一个大功能的。然后,通过应用'runState'来处理那些monad /函数的东西,runState只是将这个函数从'State'包装中取出(就像'fst'拉取一个元组的第一个元素,他们只给'runState'一个聪明的名字混淆你) – jberryman 2010-06-22 17:01:30

2

由于RandomStateState的同义词,并且没有为State定义的show的实例,因此您将无法显示它。

你也不能derive show因为State仅仅是一个函数的包装和Haskell有没有办法定义show的功能,将是有益的:

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和所有这些。

相关问题