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 muc开发者_运维技巧h in advance!!
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.
I suppose you cannot. What would be the type of the access operator? If you want dynamic random access to your data, you should convert it into a vector first.
PS: there are languages (Coq, Agda, etc.) where such access operator can be typed, but that would require dependent types (or at least type-level integers plus some magic, maybe Omega can also do that).
精彩评论