An array of infinite length in fast

I noticed one thing in Haskell that it can handle an array of infinite length with great ease.

So, being a fast programmer, I wonder how we can achieve this fast?
For instance:

 var infiniteArray = [1,2,3,.............] 
+6
source share
3 answers

Swift Array stores concrete items awaiting evaluation, so it cannot be infinite (due to finite memory).

The Swift equivalent is infinite Sequence . Here is an example that gives an infinite sequence of natural numbers.

 let naturalNumbers = sequence(first: 0, next: { $0 + 1 }) let first5NaturalNumbers = Array(naturalNumbers.prefix(5)) print(first5NaturalNumbers) 

It uses the sequence(first:next:) function to create an UnfoldSequence , which is an infinitely long, lazy evaluated sequence.

+9
source

Haskell has a lazy rating because it is a fully functional language (no side effects, etc.), Swift is not a functional language (although it borrows some functions, functionality and syntax) and does not have the same functions.

In this case, you can use Sequence and Generator to create the impression of endless lists - see http://blog.scottlogic.com/2014/06/26/swift-sequences.html , for example, Of course, the list is not infinite - by the way, the Haskell list also not infinite, it just saves the function to create new records.

The main difference is that in Haskell some basic performance optimizations are possible due to the lack of variables and side effects. In Swift, you cannot do this. So be careful when translating Haskell code to Swift.

+5
source

If you intend to pass an unknown number of parameters to a function (from a logical point of view, you cannot say โ€œan infinite number of parametersโ€ due to the memory limitations of the device), it is called a variational parameter :

A paradigm parameter accepts zero or more values โ€‹โ€‹of a given type. You use a variable parameter to indicate that the parameter may be after the function call the number of input values โ€‹โ€‹has changed. Write variable parameters by inserting three period characters (...) after the parameter type name.

For example, say you want to implement a function that takes an unknown number of Ints to sum them:

 func summationOfInfiniteInts(ints: Int...) -> Int { return ints.reduce(0, +) } let summation = summationOfInfiniteInts(ints: 1, 2, 3, 4) // 10 

Note that the ints parameter in the summationOfInfiniteInts block is represented as [Int] (an array of Int ).

Hope this helps.

+2
source

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


All Articles