Skip to content

Instantly share code, notes, and snippets.

@csain
Created October 15, 2018 19:55
Show Gist options
  • Select an option

  • Save csain/3f9da3343b21d80ff37c0d0c0e577c2a to your computer and use it in GitHub Desktop.

Select an option

Save csain/3f9da3343b21d80ff37c0d0c0e577c2a to your computer and use it in GitHub Desktop.

Revisions

  1. csain created this gist Oct 15, 2018.
    34 changes: 34 additions & 0 deletions Sample.elm
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    -- 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