From: Camil Staps Date: Sat, 18 Apr 2015 13:34:17 +0000 (+0200) Subject: fp2-w1: RandomGetallen X-Git-Url: https://git.martlubbers.net/?a=commitdiff_plain;h=d944842f1ee00d6e919d52b47798a7788477eb29;p=fp1415.git fp2-w1: RandomGetallen --- diff --git a/fp2/week1/camil/RandomGetallen.dcl b/fp2/week1/camil/RandomGetallen.dcl new file mode 100644 index 0000000..2ca4b27 --- /dev/null +++ b/fp2/week1/camil/RandomGetallen.dcl @@ -0,0 +1,7 @@ +definition module RandomGetallen + +import Random + +random_n :: Int RandomSeed -> ([Int],RandomSeed) +random_inf :: RandomSeed -> [Int] +shuffle :: [a] RandomSeed -> [a] diff --git a/fp2/week1/camil/RandomGetallen.icl b/fp2/week1/camil/RandomGetallen.icl new file mode 100644 index 0000000..a0a21bf --- /dev/null +++ b/fp2/week1/camil/RandomGetallen.icl @@ -0,0 +1,29 @@ +implementation module RandomGetallen + +import StdEnv, Random + +random_n :: Int RandomSeed -> ([Int],RandomSeed) +random_n 0 seed = ([], seed) +random_n n seed = ([r:rs], s`) +where + (rs,s`) = random_n (n-1) s + (r,s) = random seed + +random_inf :: RandomSeed -> [Int] +random_inf s = iterateSt random s + +iterateSt :: (s -> (a,s)) s -> [a] +iterateSt f s = [a : iterateSt f s`] +where + (a,s`) = f s + +shuffle :: [a] RandomSeed -> [a] +shuffle xs s = (perms xs)!!(fst (random s) rem (factorial (length xs))) + +perms :: [a] -> [[a]] +perms [] = [[]] +perms xs = [[xs!!i : xs`] \\ i <- [0..length xs - 1] , xs` <- perms (take i xs ++ drop (i+1) xs)] + +factorial :: Int -> Int +factorial 0 = 1 +factorial n = n * factorial (n-1)