Why is there no Seq.rev function?

It seems like such a complication to me. To change a sequence (enumerated), you must first transfer it to the list. Why is this?

+6
source share
4 answers

Since you cannot move backward through the sequences, lists are an ideal medium for reversing sequences. They even tend to reverse, when you build them, go to the figure.

I have no idea why rev not in the Seq module in the first place. Even LINQ has a Reverse() operator. Fortunately, it is very easy to implement.

 let rev xs = Seq.fold (fun acc x -> x::acc) [] xs 

Another option is to simply use the LINQ statement.

 let rev = System.Linq.Enumerable.Reverse 
+6
source

Why is there no rev , but there are other functions that consume the entire sequence ( length , sortBy , groupBy )? In fact, why is any function a good choice for inclusion in the standard library? I will be afraid that this is less than a set of exact rules and moreover, to hit the “sweet spot”. For example, this is a good intersection: useful, expected, executive, encouraging good practice, ... a little subjective (which is why this question is ultimately irrefutable), but practical and in most cases intuitive.

+4
source

The API on which Seq implemented has essentially two functions

  • Get the next item
  • We are at the end of the list.

As a result, there is no way to check the length of the list. Enumeration can also be very expensive since there is no caching of results and can even cause side effects.

In addition, sequences can be infinite.

As a result, we do not have Seq.rev , and we need to use the conversion to a different sequence first.

+2
source

Sequences are especially useful when you have a large, ordered set of data, but do not necessarily expect all elements to be used. Individual elements of a sequence are calculated only as necessary, so a sequence can provide better performance than a list in situations where not all elements are used http://msdn.microsoft.com/en-us/library/vstudio/dd233209.aspx

 let rnd = System.Random() let nums = seq { let rec getNext() = seq { yield rnd.Next(100) yield! getNext() } yield! getNext() } let len = nums |> Seq.length //nums is an infinite sequence, will not stop 
+2
source

Source: https://habr.com/ru/post/954220/


All Articles