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,.............]
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.
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 Sequence
s and Generator
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With