Does F# have an equivalent to Haskell's take?

前端 未结 3 1913
野趣味
野趣味 2021-01-01 19:48

In Haskell, there is a function \"take n list\" which returns the first n elements from a list. For example \"sum (take 3 xs)\" sums up the first three elements in the list

3条回答
  •  一整个雨季
    2021-01-01 20:05

    Seq.take works, as others already have stated, but all Seq operations on a list come at a cost. In the case of Seq.take, it's not surprising, as the list has to be copied.

    It's more noteworthy that, for example, Seq.concat on a list takes a lot more time than List.concat. I suppose that implies that you don't just access the list as a seq when you call a Seq.xxx function, but that the list in copied/converted to a Seq behind the scenes as well.

    edit: The reason I drew the conclusion above, was this bench using F# interactive:

    #time "on";;
    let lists = [for i in 0..5000000 -> [i..i+1]];;
    Seq.length (Seq.concat lists);;
    List.length (List.concat lists);;
    

    On my machine, the List.length version takes about 1.9 secs, whereas the Seq.length version takes about 3.8 secs (shortest time of a few repeated tests of the length lines only, excluding the list generation line).

提交回复
热议问题