Skip to content

Commit 2979e0b

Browse files
committed
Merge pull request #11 from sharkdp/fix-randomRange
Fix randomInt and randomRange to return numbers in the specified range
2 parents b750882 + 9032ebd commit 2979e0b

File tree

2 files changed

+8
-6
lines changed

2 files changed

+8
-6
lines changed

docs/Control/Monad/Eff/Random.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ or if either of `low` or `high` is not an integer.
3131

3232
For example:
3333
``` purescript
34-
randomInt (fromNumber 1) (fromNumber 10) >>= Console.print
34+
randomInt 1 10 >>= Console.print
3535
```
3636
will print a random integer between 1 and 10.
3737

@@ -46,7 +46,7 @@ value (exclusive). It is unspecified what happens if `maximum < minimum`.
4646

4747
For example:
4848
``` purescript
49-
randomRange 1 2 >>= Console.print
49+
randomRange 1.0 2.0 >>= Console.print
5050
```
5151
will print a random number between 1 and 2.
5252

src/Control/Monad/Eff/Random.purs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,24 +22,26 @@ foreign import random :: forall e. Eff (random :: RANDOM | e) Number
2222
-- |
2323
-- | For example:
2424
-- | ``` purescript
25-
-- | randomInt (fromNumber 1) (fromNumber 10) >>= Console.print
25+
-- | randomInt 1 10 >>= Console.print
2626
-- | ```
2727
-- | will print a random integer between 1 and 10.
2828
randomInt :: forall e. Int -> Int -> Eff (random :: RANDOM | e) Int
2929
randomInt low high = do
3030
n <- random
31-
pure <<< U.fromJust <<< fromNumber <<< Math.floor $ toNumber ((high - low + one) + low) * n
31+
pure <<< U.fromJust <<< fromNumber <<< Math.floor $ toNumber (high - low + one) * n + toNumber low
3232

3333
-- | Returns a random number between a minimum value (inclusive) and a maximum
3434
-- | value (exclusive). It is unspecified what happens if `maximum < minimum`.
3535
-- |
3636
-- | For example:
3737
-- | ``` purescript
38-
-- | randomRange 1 2 >>= Console.print
38+
-- | randomRange 1.0 2.0 >>= Console.print
3939
-- | ```
4040
-- | will print a random number between 1 and 2.
4141
randomRange :: forall e. Number -> Number -> Eff (random :: RANDOM | e) Number
42-
randomRange min max = (((max - min) + min) *) <$> random
42+
randomRange min max = do
43+
n <- random
44+
return (n * (max - min) + min)
4345

4446
-- | Returns a random boolean value with an equal chance of being `true` or
4547
-- | `false`.

0 commit comments

Comments
 (0)