Different argument order for getting N-th element of Array, List or Seq

て烟熏妆下的殇ゞ 提交于 2019-11-27 16:11:04

问题


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

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?


回答1:


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.

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

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

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

    




回答2:


Just use backward pipe operator:

[1..1000] |> List.nth <| 42

Since both operators are left associative, x |> f <| y is parsed as (x |> f) <| y, and this does the trick.

Backward pipe operator is also useful if you want to remove parentheses: f (very long expression) can be replaced with f <| very long expression.




回答3:


Since Pad and bytebuster answered your last question I will focus on the why part.

This is based my current knowledge and not historical facts.

Since F# derived from OCaml and OCaml has Array and List but not Seq and F# uses |> for natural pipelining and type checking and OCaml lacks the pipleline operator, the authors of F# made the switch for Seq. But obviously to be backward compatablie with OCaml they did not switch everything.



来源:https://stackoverflow.com/questions/15184949/different-argument-order-for-getting-n-th-element-of-array-list-or-seq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!