Search code examples
functional-programmingsmlsmlnj

How do I access a random member of a Tuple?


I would like to access a random member of a tuple and I'm not sure how to set #n to a variable.

Here is my code:

val lis = ("a","b","c","d")
val randNumber = Random.randRange (1,4) (Random.rand (0,1)) 
val randChar = #randNumber lis //this is where its failing

This is how I would normally access, say member #2:

val lis = ("a","b","c","d")
val ranChar = #2 lis;

So my question is how do I set #2 to a variable in the example above??

Thank you very much in advance!!


Solution

  • There are some workarounds, for example, you can explicitly match randNumber and call appropriate member functions:

        val randChar = case randNumber of
                          1 => #1 lis
                        | 2 => #2 lis
                        | 3 => #3 lis
                        | _ => #4 lis
    

    Of course, this one doesn't scale very well. Another workaround is changing representation of lis to List and use List.nth:

    List.nth(lis, randNumber-1)
    

    Hope it helps you somehow.