为什么Random类没有最小完整定义

bwr*_*oga 6 random haskell

本页指出 Random 类的最小完整定义是“Nothing”

\n

但如果我不提供它们,它们就不起作用:

\n
data Color = Red | Blue deriving (Bounded, Show)\n\ninstance Random Color\n
Run Code Online (Sandbox Code Playgroud)\n

产生编译器警告:

\n
test.hs:5:10: warning: [-Wmissing-methods]\n    \xe2\x80\xa2 No explicit implementation for\n        \xe2\x80\x98randomR\xe2\x80\x99 and \xe2\x80\x98random\xe2\x80\x99\n    \xe2\x80\xa2 In the instance declaration for \xe2\x80\x98Random Color\xe2\x80\x99\n  |\n5 | instance Random Color\n
Run Code Online (Sandbox Code Playgroud)\n

当我运行代码时出现错误:

\n
*Main> let g = mkStdGen 100\n*Main> (fst $ random g) :: Color\n*** Exception: test.hs:5:10-21: No instance nor default method for class operation random\n
Run Code Online (Sandbox Code Playgroud)\n

random为什么和没有randomR列在最小完整定义下?

\n

leh*_*ins 10

这是一个好问题。答案是:您正在使用旧版本的random,因为从random-1.2您的代码开始将无法编译,并且会产生编译时错误,大致如下:

\n
    \xe2\x80\xa2 Could not deduce (UniformRange Color)\n        arising from a use of \xe2\x80\x98System.Random.$dmrandomR\xe2\x80\x99\n      from the context: RandomGen g\n        bound by the type signature for:\n                   randomR :: forall g.\n                              RandomGen g =>\n
Run Code Online (Sandbox Code Playgroud)\n

在此之前,和random-1.2没有实现,因此编译器需要以编译警告的形式实现这些函数。然而,从 random-1.2 开始,有一个使用扩展的默认实现,这意味着只有当您的类型也有 和 实例时,您才会在没有显式实现的情况下进行编译。因此编译器不再根据需要显示and 。randomrandomRDefaultSignaturesinstance Random ColorrandomrandomRUniformUniformRangerandomrandomR

\n

编辑

\n

首先,random-1.2.1您可以使用很好的辅助函数创建一个实例uniformEnumMuniformEnumRM

\n
import System.Random.Stateful\n\ndata Color = Red | Blue deriving (Bounded, Enum, Show)\n\ninstance Uniform Color where\n  uniformM = uniformEnumM\n\ninstance Uniform Color where\n  uniformRM = uniformEnumRM\n\ninstance Random Color\n
Run Code Online (Sandbox Code Playgroud)\n

  • @bwroga不,函数[**是**/被列出](https://hackage.haskell.org/package/random-1.1/docs/System-Random.html#t:Random)作为最低要求!只是,这在该软件包的最新版本中发生了变化,这是您在在线文档中查找的内容,但似乎并未实际使用。 (3认同)
  • @bwroga,正如 leftaroundabout 所指出的,您正在查看较新版本的库(random-1.2.1)的文档,但您正在使用旧版本(random-1.1) (2认同)