Created
May 2, 2025 13:50
-
-
Save nrinaudo/15d607356a1bbe7a6a71c21721eeef2f to your computer and use it in GitHub Desktop.
Random Capability Passing Style
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package rand | |
import scala.util.Random | |
type Rand[A] = Random ?=> A | |
inline def apply[A](body: Rand[A]): A = body(using new Random) | |
val int: Rand[Int] = r ?=> r.nextInt | |
val bool: Rand[Boolean] = r ?=> r.nextBoolean | |
def range(min: Int, max: Int): Rand[Int] = | |
val intervalLength = max.toLong - min.toLong | |
val totalLength = (Int.MaxValue.toLong - Int.MinValue.toLong).toDouble | |
((int - Int.MinValue.toLong) / totalLength * intervalLength + min).toInt | |
val lowerAscii: Rand[Char] = range('a'.toInt, 'z'.toInt).toChar | |
val upperAscii: Rand[Char] = range('A'.toInt, 'Z'.toInt).toChar | |
val digit: Rand[Char] = range('0'.toInt, '9'.toInt).toChar | |
def oneOf[A](rands: Rand[A]*): Rand[A] = rands(range(0, rands.length)) | |
val alpha: Rand[Char] = oneOf(lowerAscii, upperAscii) | |
val alphaNum: Rand[Char] = oneOf(lowerAscii, upperAscii, digit) | |
def listOfN[A](n: Int, ra: Rand[A]): Rand[List[A]] = | |
if n <= 0 then Nil | |
else ra :: listOfN(n - 1, ra) | |
def list[A](size: Rand[Int], ra: Rand[A]): Rand[List[A]] = | |
listOfN(size, ra) | |
def identifier: Rand[String] = | |
(oneOf(alpha) :: list(range(0, 9), alphaNum)).mkString |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment