获取数组、列表或序列的第 N 个元素的不同参数顺序 [英] Different argument order for getting N-th element of Array, List or Seq

查看:24
本文介绍了获取数组、列表或序列的第 N 个元素的不同参数顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在获取数组、列表或序列的第 N 个元素的函数中使用不同的参数顺序是否有充分的理由:

Is there a good reason for a different argument order in functions getting N-th element of Array, List or Seq:

Array.get source index
List .nth source index
Seq  .nth index  source

我想使用管道运算符,但似乎只能使用 Seq:

I would like to use pipe operator and it seems possible only with Seq:

s |> Seq.nth n

有没有办法让数组或列表具有相同的表示法?

Is there a way to have the same notation with Array or List?

推荐答案

我想不出有什么好的理由来定义 Array.getList.nth 这个大大地.鉴于流水线在 F# 中非常常见,它们应该被定义为 source 参数放在最后.

I don't think of any good reason to define Array.get and List.nth this way. Given that pipeplining is very common in F#, they should have been defined so that the source argument came last.

List.nth的情况下,变化不大,因为你可以使用Seq.nth,时间复杂度仍然是O(n) 其中 n 是列表的长度:

In case of List.nth, it doesn't change much because you can use Seq.nth and time complexity is still O(n) where n is length of the list:

[1..100] |> Seq.nth 10

在数组上使用 Seq.nth 不是一个好主意,因为会丢失随机访问.为了保持Array.getO(1)运行时间,可以定义:

It's not a good idea to use Seq.nth on arrays because you lose random access. To keep O(1) running time of Array.get, you can define:

[<RequireQualifiedAccess>]
module Array =
    /// Get n-th element of an array in O(1) running time
    let inline nth index source = Array.get source index

一般来说,使用flip函数可以缓解不同的参数顺序:

In general, different argument order can be alleviated by using flip function:

let inline flip f x y = f y x

你可以直接在上面的函数上使用:

You can use it directly on the functions above:

[1..100] |> flip List.nth 10
[|1..100|] |> flip Array.get 10

这篇关于获取数组、列表或序列的第 N 个元素的不同参数顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆