summaryrefslogtreecommitdiff
path: root/Haskell-book/23/RandomExample/src/RandomExample2.hs
diff options
context:
space:
mode:
authorEugen Wissner <belka@caraus.de>2025-12-11 10:28:11 +0100
committerEugen Wissner <belka@caraus.de>2025-12-11 10:28:11 +0100
commit98329e0a3dd4f78b5d815ac3896272ec70904901 (patch)
tree80f9c56cfe2ac20232358f236d32e84bd683be1b /Haskell-book/23/RandomExample/src/RandomExample2.hs
parent3624c712d72d246f21d4e710cec7c11e052e0326 (diff)
downloadbook-exercises-98329e0a3dd4f78b5d815ac3896272ec70904901.tar.gz
Add remaining haskell book exercises
Diffstat (limited to 'Haskell-book/23/RandomExample/src/RandomExample2.hs')
-rw-r--r--Haskell-book/23/RandomExample/src/RandomExample2.hs54
1 files changed, 54 insertions, 0 deletions
diff --git a/Haskell-book/23/RandomExample/src/RandomExample2.hs b/Haskell-book/23/RandomExample/src/RandomExample2.hs
new file mode 100644
index 0000000..6fbd821
--- /dev/null
+++ b/Haskell-book/23/RandomExample/src/RandomExample2.hs
@@ -0,0 +1,54 @@
+module RandomExample2 where
+
+import Control.Applicative (liftA3)
+import Control.Monad (replicateM)
+import Control.Monad.Trans.State
+import System.Random
+import RandomExample
+
+rollDie :: State StdGen Die
+rollDie = state $ do
+ (n, s) <- randomR (1, 6)
+ return (intToDie n, s)
+
+rollDie' :: State StdGen Die
+rollDie' = intToDie <$> state (randomR (1, 6))
+
+rollDieThreeTimes' :: State StdGen (Die, Die, Die)
+rollDieThreeTimes' = liftA3 (,,) rollDie rollDie rollDie
+
+infiniteDie :: State StdGen [Die]
+infiniteDie = repeat <$> rollDie
+
+nDie :: Int -> State StdGen [Die]
+nDie n = replicateM n rollDie
+
+rollsToGetTwenty :: StdGen -> Int
+rollsToGetTwenty g = go 0 0 g
+ where
+ go :: Int -> Int -> StdGen -> Int
+ go sum count gen
+ | sum >= 20 = count
+ | otherwise =
+ let (die, nextGen) = randomR (1, 6) gen
+ in go (sum + die) (count + 1) nextGen
+
+rollsToGetN :: Int -> StdGen -> Int
+rollsToGetN limit g = go 0 0 g
+ where
+ go :: Int -> Int -> StdGen -> Int
+ go sum count gen
+ | sum >= limit = count
+ | otherwise =
+ let (die, nextGen) = randomR (1, 6) gen
+ in go (sum + die) (count + 1) nextGen
+
+rollsCountLogged :: Int -> StdGen -> (Int, [Die])
+rollsCountLogged limit g = go 0 0 g []
+ where
+ go :: Int -> Int -> StdGen -> [Die] -> (Int, [Die])
+ go sum count gen dies
+ | sum >= limit = (count, dies)
+ | otherwise =
+ let (die, nextGen) = randomR (1, 6) gen
+ in go (sum + die) (count + 1) nextGen ((intToDie die) : dies)