Haskell Random不能构造无限类型:a1 = IO a1 [英] Haskell Random cannot construct the infinite type: a1 = IO a1

查看:87
本文介绍了Haskell Random不能构造无限类型:a1 = IO a1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Haskell生成一个有26个随机整数的列表,总和为301。我写了以下内容:

$ $ p $ import System.Random

f 1 sum = $
fn sum = m:(f(n-1)(sum-m))
其中m = randomRIO(0,sum)

但它不能编译!我感到困惑于IO!
$ b

 =lang-none prettyprint-override> 发生检查:无法构造无限类型:a1 = IO a1 
在'(:)'的第一个参数中,即`m'
在表达式中:m:(f(n - 1)(sum - m))
在等式'f':
fn sum
= m:(f(n - 1)(sum - m))
其中
m = randomRIO(0,sum)


解决方案

在这种情况下,错误信息有点令人困惑,需要在 IO monad中工作,因为它使用 IO 中的 randomRIO code>,并且(设计上)无法从非 - IO 代码运行 IO 代码。

  f 1 sum = return 
fn sum = do
x < - randomRIO(0 ,总和)
xs <-f(n-1)(sum-x)
return(x:xs)


I want to generate a list with 26 random integers which sum is 301 with Haskell. I write the following:

import System.Random

f 1 sum = [sum]
f n sum = m : (f (n-1) (sum-m))
    where m = randomRIO (0,sum)

but it can't be compiled! I am confused with IO!

Occurs check: cannot construct the infinite type: a1 = IO a1
In the first argument of `(:)', namely `m'
In the expression: m : (f (n - 1) (sum - m))
In an equation for `f':
    f n sum
      = m : (f (n - 1) (sum - m))
      where
          m = randomRIO (0, sum)

解决方案

The error message is somewhat confusing in this case, but the punchline is that you need to work in the IO monad, since it's using randomRIO which is in IO, and there is (by design) no way to run IO code from non-IO code.

f 1 sum = return [sum]
f n sum = do
  x  <- randomRIO (0, sum)
  xs <- f (n - 1) (sum - x)
  return (x : xs)

这篇关于Haskell Random不能构造无限类型:a1 = IO a1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆