列表或序列的第N个元素的不同参数顺序

列表或序列的第N个元素的不同参数顺序

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

问题描述

在获取Array,List或Seq的第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

是否可以对Array或List使用相同的符号?

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并不是一个好主意,因为您会丢失随机访问权限.要使O(1)的运行时间保持为Array.get,您可以定义:

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个元素的不同参数顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 15:09