如何将随机数添加到列表中 [英] How to append random number to a list
问题描述
我写了一个函数来产生随机数:
drawFloat :: Float - >浮动 - > IO Float
drawFloat xy = getStdRandom(randomR(x,y))
列表 [1,2,3]
。
如何将随机数附加到此列表中?
我试过 [1,2,3] ++(drawFloat 2 10)
错误消息:
无法匹配预期类型'[ a]'与实际类型'IO a0'
相关联的绑定包括它:: [a](绑定在< interactive> 72:1)
在'(++)'的第二个参数,即'(drawFloat 2 10)'
在表达式中:[1,2,3] ++(drawFloat 2 10)
我也试过 [1,2,3] ++ [(drawFloat 2 10)]
。仍然没有工作。所以, drawFloat
的类型是 浮动 - >浮动 - > IO Float
。我们只能附加一个 [Float]
。尝试
appendRand :: [Float] - > IO [Float]
appendRand lis =(lis ++)。返回< $> drawFloat 2 10
这里我们提升函数(list ++)。 return :: Float - > [Float]
改为 IO Float - > IO [Float]
这正是我们想要的。 (这里, return
正在 []
monad上运行,而不是 IO
)
I wrote a function to generate random number:
drawFloat :: Float -> Float -> IO Float
drawFloat x y = getStdRandom (randomR (x,y))
Now I have a list [1,2,3]
.
How can I append the random number to this list?
I tried [1,2,3] ++ (drawFloat 2 10)
It did not work...
ERROR Message:
Couldn't match expected type ‘[a]’ with actual type ‘IO a0’
Relevant bindings include it :: [a] (bound at <interactive>:72:1)
In the second argument of ‘(++)’, namely ‘(drawFloat 2 10)’
In the expression: [1, 2, 3] ++ (drawFloat 2 10)
I also tried [1,2,3] ++ [(drawFloat 2 10)]
. Still not work..
So, the type of drawFloat
is Float -> Float -> IO Float
. We can only append a [Float]
. Try
appendRand :: [Float] -> IO [Float]
appendRand lis = (lis ++) . return <$> drawFloat 2 10
Here we are elevating the function (list ++) . return :: Float -> [Float]
to a IO Float -> IO [Float]
which is exactly what we want. (Here, return
is operating on the []
monad, not IO
)
这篇关于如何将随机数添加到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!