Reputation: 2239
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..
Upvotes: 0
Views: 194
Reputation: 34292
Because drawFloat
returns a monadic type, you'll have to dive into the same monad in order to append:
import System.Random
drawFloat :: Float -> Float -> IO Float
drawFloat x y = getStdRandom (randomR (x,y))
appendRandom :: [Float] -> IO [Float]
appendRandom as = do
val <- drawFloat 2 10
return $ as ++ [val]
main = appendRandom [1, 2, 3] >>= print
Upvotes: 1
Reputation: 13042
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
)
Upvotes: 3