1

我有元组type foo = (string, string);

  1. 如何创建类型 -foo元组数组?

  2. 如果使用元组数组或元组列表有什么区别?

  3. 如何访问元组值数组?JS模拟:

    const foo1 = [1, 2];
    const foo2 = [3, 4];
    const arrayOfFoo =[foo1, foo2];
    
    console.log(arrayOfFoo[0][0]) // 1
    console.log(arrayOfFoo[1][1]) // 4
    

更新:我发现了优秀的 gitbook

https://kennetpostigo.gitbooks.io/an-introduction-to-reason/content/

/* create tuple type*/
type t = (int, int);

/* create array of tuples */
type arrayOfT = array t;

/* create array of tuples */
type listOfT = list t;

/* create list of tuples value */
let values: listOfT = [(0, 1), (2, 3)];

/* get first tuple  */
let firstTyple: t = List.nth values 0;

/* get first tuple values  */
let (f, s) = firstTyple;

这个对吗?有没有更有用的方法来做到这一点?

4

1 回答 1

4
  1. let x: list (int, int) = [(1,2), (3,4)] /* etc */

2.

  • Array固定长度和可变的,并提供简单的随机访问。它与 JavaScript 列表非常相似。将它用于比追加/弹出更多需要随机访问(读/写)的事情。
  • AList是一个单链表并且是不可变的。来自功能传统的人们会很熟悉。将它用于访问第一个元素或从前面推送/弹出比随机访问更常见的事情。

在实践中,我几乎将 List 用于所有内容,但 Array 用于一些性能密集型情况。

3.

从列表中获取第一件事是非常常见的。通常,您既想对第一件事做某事,又想对列表的“其余部分”做一些事情。为了彻底,您还想处理列表为空的情况。看起来是这样的:

switch (somelist) {
  | [] => Js.log "nothing there" /* what we do if the list is empty */
  | [firstItem, ...rest] => Js.log firstItem /* we have things! */
}

如果您只想获取第一个项目,并且如果您的程序碰巧是空的,那么您的程序会崩溃,您可以执行List.hd mylist.

从元组中获取项目就像你放的一样,let (a, b) = sometuple. 如果你只关心第一个,你可以这样做let (a, _) = sometuple_是一个特殊的占位符,意思是“我不在乎这是什么”)。对于长度为 2 的元组,有特殊的辅助函数fstsnd,它可以为您提供第一个和第二个项目。

于 2017-06-06T21:58:41.960 回答