reasonml - 数组或元组列表

reasonml - array or list of tuples

我有元组 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;

这是正确的吗?还是有更好的方法来做到这一点?

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

2.

  • 一个 Array 固定长度和可变的,并提供简单的随机访问。它与 JavaScript 列表非常相似。将它用于比 append/pop.
  • 更需要随机访问 (read/write) 的事物
  • A List 是一个单链表并且是不可变的。来自功能传统的人们会很熟悉。将它用于从前面访问第一个元素或 pushing/popping 比随机访问更常见的事情。

在实践中,我对几乎所有内容都使用 List,但在某些性能密集型情况下使用 Array。

3.

从列表中获取第一件事是非常常见的。通常,您希望同时对第一件事做某事,然后对列表的 "rest" 做某事。为彻底起见,您还需要处理列表为空的情况。这是它的样子:

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_ 是一个特殊的占位符,意思是 "I don't care what this is")。对于长度为 2 的元组,有特殊的辅助函数 fstsnd,它们可以为您获取第一项和第二项。