Skip to content

Instantly share code, notes, and snippets.

@csain
Created October 15, 2018 19:55
Show Gist options
  • Save csain/3f9da3343b21d80ff37c0d0c0e577c2a to your computer and use it in GitHub Desktop.
Save csain/3f9da3343b21d80ff37c0d0c0e577c2a to your computer and use it in GitHub Desktop.
-- Given a list of items and a seed int (such as a current timestamp), sample an item from a list.
module Helpers.Sample exposing (sample)
import List.Extra
import Random
import Tuple
randomInt : { min : Int, max : Int, seed : Int } -> Int
randomInt { min, max, seed } =
-- This function returns a pseudorandom integer within a range based on a seed
-- Random.initialSeed creates a reproducable sequence of pseudorandom values
-- Random.int returns a 'Generator Int' within a range [min, max]
-- Random.step returns an (a, Seed) where 'a' is a generator type
Random.step (Random.int min max) (Random.initialSeed seed)
|> Tuple.first
sample : List a -> Int -> Maybe a
sample items seed =
-- Sample a random item from a list
-- by choosing a random index within the range of the length of the list
let
index : Int
index =
randomInt
{ min = 0
, max = List.length items - 1
, seed = seed
}
in
items
|> List.Extra.getAt index
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment