Question: Infinite length array in swift

Question

Infinite length array in swift

Answers 3
Added at 2016-12-29 08:12
Tags
Question

I noticed one thing in Haskell that it efficiently handle working with infinite length array with great ease.

So being swift programmer, I am curious about how we can achieve this with swift?
For example:

var infiniteArray = [1,2,3,.............]
Answers
nr: #1 dodano: 2016-12-29 08:12

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

That being said you can use Sequences and Generators to create the impression of infinite lists - see http://blog.scottlogic.com/2014/06/26/swift-sequences.html for example. Of course the list is not really infinite - btw the Haskell list isn't infinite either, it just stores the function to create new entries.

The main difference is that in Haskell there are some major performance optimisations possible due to the lack of variables and side effects. In Swift you cannot do that. So be careful translating Haskell code to Swift.

nr: #2 dodano: 2016-12-29 08:12

If your intention to pass unknown number of parameters to a function (from a logical viewpoint, you can't say "infinite number of parameters" because of the limitation of the machine's memory), it's called variadic parameter:

A variadic parameter accepts zero or more values of a specified type. You use a variadic parameter to specify that the parameter can be passed a varying number of input values when the function is called. Write variadic parameters by inserting three period characters (...) after the parameter’s type name.

For example, let's say that you want to implement a function that takes 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 ints parameter in the block of summationOfInfiniteInts represented as [Int] (array of Int).

Hope this helped.

nr: #3 dodano: 2016-12-29 09:12

Swift's Array stores concrete, eagerly evaluated elements, so it can't be infinite (due to finite memory).

The Swift equivalent is an infinite Sequence. Here's an example that produces the 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 produce an UnfoldSequence, which is an infinitely long, lazy evaluated sequence.

Source Show
◀ Wstecz