如何访问元组的随机成员?

发布于 2024-11-01 04:22:43 字数 406 浏览 0 评论 0原文

我想访问元组的随机成员,但不确定如何将 #n 设置为变量。

这是我的代码:

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

这是我通常访问的方式,比如成员#2:

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

所以我的问题是如何将 #2 设置为上面示例中的变量?

预先非常感谢!

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!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挽心 2024-11-08 04:22:43

有一些解决方法,例如,您可以显式匹配 randNumber 并调用适当的成员函数:

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

当然,这个方法的扩展性不是很好。另一种解决方法是将 lis 的表示更改为 List 并使用 List.nth

List.nth(lis, randNumber-1)

希望它能以某种方式帮助您。

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.

风为裳 2024-11-08 04:22:43

我想你不能。访问运算符的类型是什么?
如果您想要动态随机访问数据,您应该首先将其转换为向量。

PS:有些语言(Coq、Agda 等)可以输入此类访问运算符,但这需要依赖类型(或者至少是类型级整数加上一些魔法,也许 Omega 也可以做到这一点)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文