Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add cats.effect.std.Random doc page #2213

Merged
merged 2 commits into from
Aug 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions docs/std/random.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
---
id: random
title: Random
---

A purely-functional implementation of a source of random information.

```scala
trait Random[F[_]] {
def nextInt: F[Int]

def shuffleList[A](list: List[A]): F[List[A]]

// ... and more
}
```

## API

The API of `Random` is created to closely resemble the `scala.util.Random` API,
so it should be fairly approachable to people familiar with the
[standard library](https://www.scala-lang.org/api/2.13.6/scala/util/Random.html).

Users can expect to find all methods available on a Scala standard library
`Random` instance also available on instances of this type class (with some
minor renamings to avoid method overloading, e.g. `betweenLong`,
`betweenDouble`, etc).

## Customizing the source of randomness

`cats.effect.std.Random` can be backed by a variety of random sources available
on the JVM:
- `scala.util.Random` (`Random.scalaUtilRandom[F: Sync]`)
- Individual instances can be customized with an initial seed, or load
balanced between several `scala.util.Random` instances
- `java.util.Random`
- `java.security.SecureRandom`

## Creating a `Random` instance

Obtaining an instance of `Random` can be as simple as:
```scala mdoc:silent
import cats.effect.IO
import cats.effect.std.Random

Random.scalaUtilRandom[IO]
```

## Using `Random`
```scala mdoc
import cats.Functor
import cats.syntax.functor._

def dieRoll[F[_]: Functor: Random]: F[Int] =
Random[F].betweenInt(0, 6).map(_ + 1) // `6` is excluded from the range
```

## Derivation

An instance of `cats.effect.std.Random` can be created by any data type
capable of synchronously suspending side effects (i.e. `Sync`). Furthermore,
`Random` instances for monad transformers can be automatically derived for any
data type for which an instance of `Random` can already be derived.
1 change: 1 addition & 0 deletions site-docs/sidebars.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"std/hotswap",
"std/pqueue",
"std/queue",
"std/random",
"std/ref",
"std/resource",
"std/semaphore",
Expand Down