random - How to easily shuffle a list in sml? -


how can shuffle list of tuples in sml? there doesn't seem built in function so.

i assume need use random number generator how move items in list have no idea.

this moscow ml's random library. sml/nj's random library, have adjust random functions slightly.

val _ = load "random" val rng = random.newgen ()  (* select([5,6,7,8,9], 2) = (7, [5,6,8,9]) *) fun select (y::xs, 0) = (y, xs)   | select (x::xs, i) = let val (y, xs') = select (xs, i-1) in (y, x::xs') end   | select (_, i) = raise fail ("short " ^ int.tostring ^ " elements.")  (* recreates list in random order removing elements in random positions *) fun shuffle xs =     let fun rtake [] _ = []           | rtake ys max =             let val (y, ys') = select (ys, random.range (0, max) rng)             in y :: rtake ys' (max-1)             end     in rtake xs (length xs) end 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -