[Haskell-cafe] Re: Random question
Iain Barnett
iainspeed at gmail.com
Sun Oct 5 07:54:24 EDT 2008
I just wanted to say thanks to everyone that helped me on this. I'm
still reading/cogitating the stuff you gave me, but I did manage to
write a Fisher-Yates shuffle using random numbers. I had a lightbulb
moment while reading about sequence (so I suppose that might count as
my 7th Monad tutorial :). The <- takes values out of monads[1]. So
simple!
-- let c = [11..18]
--shuff (length c) c
shuff :: Int -> [a] -> IO [a]
shuff 0 xs = return xs
shuff (len + 1) xs = (rand 1 (len + 1)) >>= \r -> shuff len $ requeue
r xs
where requeue = \z xs -> (init $ take z xs) ++ (drop z xs) ++
[last $ take z xs]
rand :: Int -> Int -> IO Int
rand low high = getStdRandom (randomR (low,high))
Since it's recursive I suspect there may be a way to do this with a
fold, but I'll probably work that out at a later lightbulb moment
(after more questions:)
Thanks again.
Iain
[1] In a lot of IO tutorials it just seems to be the 'do' syntax for
assigning a value to a symbol, but of course,
:t getLine
getLine :: IO String
On 24 Sep 2008, at 10:03 pm, Iain Barnett wrote:
> Hi,
>
> I have a function, that produces a random number between two given
> numbers
>
> rand :: Int -> Int -> IO Int
> rand low high = getStdRandom (randomR (low,high))
>
>
> (Naively) I'd like to write something like
>
> take (rand 1 10 ) [1..10]
>
> and see [1,2,3,4] ... or anything but nasty type-error messages.
>
>
>
> I'm reading about 6 tutorials on monads simultaneously but still
> can't crack this simple task, and won't pain you with all the
> permutations of code I've already tried. It's a lot, and it ain't
> pretty.
>
> Would anyone be able to break away from C/C++ vs Haskell to help?
> Just a point in the right direction or a good doc to read, anything
> that helps will be much appreciated.
>
>
> Regards
> Iain
More information about the Haskell-Cafe
mailing list