Introducing Elm Random List

The Elm standard library offers a random list generation function that works great. Having looked at its implementation , we see that the list is built in the style of the functional, that is, from the end to the beginning. When enough elements are generated, the return list is returned:

if n < 1 then
    (List.reverse list, seed)

I wonder why we need to cancel this list? Is it necessary to ensure the "right" randomness?

+4
source share
3 answers

The call List.reverseactually returns the list in the order in which it was generated.

Here is the code for the functions in question:

list : Int -> Generator a -> Generator (List a)
list n (Generator generate) =
  Generator <| \seed ->
    listHelp [] n generate seed

listHelp : List a -> Int -> (Seed -> (a,Seed)) -> Seed -> (List a, Seed)
listHelp list n generate seed =
  if n < 1 then
    (List.reverse list, seed)
  else
    let
      (value, newSeed) =
        generate seed
    in
      listHelp (value :: list) (n-1) generate newSeed

Int , , (seed, seed + 1), , , 1 ( 5 ):

listHelp [] 5 myGen 1 -- initial state
listHelp [1] 4 myGen 2
listHelp [2,1] 3 myGen 3
listHelp [3,2,1] 2 myGen 4
listHelp [4,3,2,1] 1 myGen 5
listHelp [5,4,3,2,1] 0 myGen 6

, [1,2,3,4,5].

, , , .

, (, initialSeed - 1).

List.head (list 5 (myGen initialSeed)) == Just 5
List.head (list 4 (myGen initialSeed)) == Just 4

Seed , , , list . List.reverse .

+3

, . , . , .

, , , .. . , . , api .

+1

because we can add one value to the list, and we can only add the list to the list. We could

append list [value]

and then we don’t need to change it

http://package.elm-lang.org/packages/elm-lang/core/latest/List

0
source

Source: https://habr.com/ru/post/1625964/


All Articles