Uses “Recursion” concept to iterate collection data in Functional Programming - loops

I read some papers and documents that said that Functional Programming uses “recursion” concept to iterate collection data, while OOP uses “loop” concept to iterate collection data (for example:- the for-each loop in Java). So I'm confused about that statement. And I have three questions
Is it a good practice when I use “loop” in Functional Programming?
If not, can anyone tell me what method I should use?
Can anyone give me an example and comparison about two methods of iterating Collection Data?

Your question is somewhat unclear, for instance
Is it a good practice when I use “loop” in Functional Programming?
What would a loop construct be inside a functional programming language? Several functional programming languages lack explicit loop statements (for-each, for, while, do-while, ...)
Regardless, in order:
Is it a good practice when I use “loop” in Functional Programming?
Any attempt to express a loop using an imperative style is usually considered as a poor practice. As previously stated, many functional programming (FP) languages lack such constructs.
If not, can anyone tell me what method I should use?
You can read about recursion at Wikipedia.
Many data structures, such as lists, are recursive by nature so iterating across them recursively should feel rather natural.
Can anyone give me an example and comparison about two methods of iterating collection data?
Let's us iterate across a list using some pseudo-code,
Imperative style
A couple of imperative examples that map to different looping constructs.
For-each
list = [1, 2, 3]
for element in list:
print element
While
Let len be a function that returns the length of the list, and let lists be zero-indexed, so that list[0] == 1,
list = [1, 2, 3]
i = 0
while i < len(list):
print element
i++
Functional style
Using recursion:
Let head(list) be a function that returns the first element of the list and tail(list) return all elements after the head
list = [1, 2, 3]
def loop(list):
if list == []: # Check if the list is empty
return
print head(list)
loop(tail(list))
There are other ways to iterate across lists in many FP languages, most notably map and list-comprehensions but I'll leave that out for now.

Related

How does Ruby's Combined Comparison Operator work?

First question on stackoverflow :)
I'm going through the Ruby course on Codecademy and I'm stuck on something.
fruits = ["orange", "apple", "banana", "pear", "grapes"]
fruits.sort! {|first, second| second <=> first}
print fruits
I don't know how to phrase this question. On Codecademy the assignment was to set up the array to be displayed in reverse on the console. After some research, I was able to figure it out. I understand how it works and the order to put it in the code not why. I'm aware that "<=>" compares two objects, but how do the items within the array become objects when we don't declare them as such?
Secondly, what is the purpose of writing this code in this way when we could do fruits.sort.reverse?
First question: At various points in its operation the sort method has to compare pairs of objects to see what their relative ordering should be. It does the comparison by applying the block you pass to sort, i.e., {|first, second| second <=> first}. Not sure what you mean by "how do the items within the array become objects when we don't declare them as such?". All data in ruby is an object, so there's no declaration or conversion needed given that all variables are object references.
Second question: Yes, you could do fruits.sort.reverse, but that would require additional work after the sort to do the reverse operation. Also, reverse can't handle more complex sorting tasks, such as sorting people by multiple criteria such as gender & last name, or hair color, height, and weight. Writing your own comparator can handle quite complex orderings.
String literals can be used to create string objects in Ruby, there is no need to use the String class to create the object. The following two are equivalent:
"Hello, world!"
String.new("Hello, world!")
More information can be found here.
Secondly, what is the purpose of writing this code in this way when we could do fruits.sort.reverse?
Please contact Codecademy about this, but I suspect it's for learning more about how <=> works.

How to handle nested array with >> and return a flat array?

I wonder weather there is a concise way in Raku to process a nested array (array of arrays) and
flatten the result? When transforming flat arrays >>. is handy, but if I want to return arrays and the result should be flat, what construct is avaiblable in Raku?
grammar g {
rule port { <pnamelist> + %% ","}
token pnamelist { <id> + }
token id { \w }
}
class a {
method port ($/) { make $<pnamelist>>>.made }
method pnamelist ($/) { make $<id>>>.made }
method id ($/ ) { make $/.Str }
}
my $r = g.parse("ab,cd", :rule('port'), :actions(a) ).made;
say $r; # [[a b] [c d]]
The above snippet outputs [[a b] [c d]], however what I actually want is [a b c d] . Is there a concise way to rewrite make $<pnamelist>>>.made so that it iterates over array $<pnamelist> and gathers each elements .made in a flat list what is then input for ``make` ?
TL;DR Flatten using positional subscripting. For your example, append [*;*] or [**] to $<pnamelist>>>.made. You'll get the same result as Liz's solution.
Why use this solution?
Liz is right that map and relatives (for, deepmap, duckmap, nodemap, and tree) are more flexible, at least collectively, and combining them with .Slip can be just the ticket.
But I often I find it cognitively simpler to use these tools, and others, including hypers, to create whatever data structure, without worrying about .Sliping, and then just flatten the result at the end by just appending [*;*...] or [**] as explained below.
Last but not least, it's simple and succinct:
method port ($/) { make $<pnamelist>>>.made[**] }
^^^^
Flattening N levels deep with [*;*...]
The general approach for flattening N levels deep works today as #Larry always intended.
The first Whatever strips away the outer array; each additional Whatever, separated by a ;, peels away another inner level of nesting. For your current example two Whatevers does the job:
method port ($/) { make $<pnamelist>>>.made[*;*] }
^^^^^
This yields the same result as Liz's solution:
(a b c d)
If you want the end result to have an outer array, just add it to the end result wherever you think appropriate, eg:
method port ($/) { make [ $<pnamelist>>>.made[**] ] }
Bulldozing with [**]
If you want to bulldoze a nested array/list, peeling away all nesting no matter how deep, you could just write more *;s than you can possibly need. Any extras won't make any difference.
But the desire to bulldoze is natural enough, and comes up often enough, that it makes sense to have an operation that does it without needing a hacky notion like "just write lots of *;".
So it should come as no surprise that #Larry specified such a bulldozing operation a decade or so ago. It's nicely consistent with the rest of Raku's feel, using a HyperWhatever (**) as an indexing value.
But trying it:
method port ($/) { make $<pnamelist>>>.made[**] }
^^^^
currently yields:
HyperWhatever in array index not yet implemented. Sorry.
Fortunately one can very easily "fake" it:
sub postfix:< [**] > (\lhs) { gather lhs.deepmap: *.take }
The body of the postfix comes from here.
With this in place then changing the [*;*] to [**] will work for your example but will continue to work no matter how deeply nested its left hand side is.
And presuming HyperWhatever in array index is one day implemented as a built in, one will be able to remove the postfix definition and any code using it will work without it -- and, presumably, get a speedup.
make $<pnamelist>.map(*.made.Slip)
When you slip a list of values in a map, they get flattened.
Using >>. is nice in many cases, but personally I prefer .map as it allows for more flexibility.

Linked lists in Swift

I decided to polish my knowledge of data structures and came across linked list.
I was wondering if anyone has any practical example of where do we use them in relation to mobile development or any other kind of projects that use swift as their language since to me it seems the Array class already has enough flexibility as it is.
You should use linked lists anytime you need their primary benefit: O(1) insertion and deletion at arbitrary points in the list.
The mistake most people make with linked lists is trying to implement them as a value type in Swift. That's very hard, and the resulting data structure is generally useless. The most common form is with an enum:
enum List<T> {
indirect case Cons(T, List<T>)
case Nil
}
let list = List.Cons(1, .Cons(2, .Cons(3, .Nil)))
I've never seen anyone come up with an efficient implementation of that. Efficient collections in Swift require copy-on-write, and that's very hard to build for an enum.
The natural way to build linked lists in Swift is as a mutable reference type. That's very easy to make efficient and is very useful.
class List<T> {
var value: T
var next: List<T>?
init(_ value: T, _ next: List<T>?) {
self.value = value
self.next = next
}
}
let list = List(1, List(2, List(3, nil)))
And in that form, you'd use it any time you want O(1) insertion and deletion at arbitrary points in the list.
You could also build this as an immutable reference type (using let) if you had several large lists that shared a significant tail. I've never seen that come up in practice.
Most folks I know who go down this route want an immutable linked list so they can implement the many very beautiful recursive algorithms that are built on them and which are very common in FP languages (this may say more about the people I know than the question itself). But Swift is at best mildly hostile to recursion, so this is rarely worth the trouble IMO except as an exercise. But recursive algorithms are just one use of linked lists. As an O(1) arbitrary-insertion data structure they're as useful in Swift as they are in Pascal and C, and you build them roughly the same way.

Explanation of splat

While reading about Julia on http://learnxinyminutes.com/docs/julia/ I came across this:
# You can define functions that take a variable number of
# positional arguments
function varargs(args...)
return args
# use the keyword return to return anywhere in the function
end
# => varargs (generic function with 1 method)
varargs(1,2,3) # => (1,2,3)
# The ... is called a splat.
# We just used it in a function definition.
# It can also be used in a fuction call,
# where it will splat an Array or Tuple's contents into the argument list.
Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # produces a Set of Arrays
Set([1,2,3]...) # => Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3)
x = (1,2,3) # => (1,2,3)
Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples
Set(x...) # => Set{Int64}(2,3,1)
Which I'm sure is a perfectly good explanation, however I fail to grasp the main idea/benefits.
From what I understand so far:
Using a splat in a function definition allows us to specify that we have no clue how many input arguments the function will be given, could be 1, could be 1000. Don't really see the benefit of this, but at least I understand (I hope) the concept of this.
Using a splat as an input argument to a function does... What exactly? And why would I use it? If I had to input an array's contents into the argument list, I would use this syntax instead: some_array(:,:) (for 3D arrays i would use some_array(:,:,:) etc.).
I think part of the reason why I don't understand this is that I'm struggling with the definition of tuples and arrays, are tuples and arrays data types (like Int64 is a data type) in Julia? Or are they data structures, and what is a data structure? When I hear array I typically think about a 2D matrix, perhaps not the best way to imagine arrays in a programming context?
I realize that you could probably write entire books about what a data structure is, and I could certainly Google it, however I find that people with a profound understanding of a subject are able to explain it in a much more succinct (and perhaps simplified) way then let's say the wikipedia article could, which is why I'm asking you guys (and girls).
You seem like you get the mechanism and how/what they do but are struggling with what you would use it for. I get that.
I find them useful for things where I need to pass an unknown number of arguments and don't want to have to bother constructing an array first before passing it in when working with the function interactively.
for instance:
func geturls(urls::Vector)
# some code to retrieve URL's from the network
end
geturls(urls...) = geturls([urls...])
# slightly nicer to type than building up an array first then passing it in.
geturls("http://google.com", "http://facebook.com")
# when we already have a vector we can pass that in as well since julia has method dispatch
geturls(urlvector)
So a few things to note. Splat's allow you to turn an iterable into an array and vice versa. See the [urls...] bit above? Julia turns that into a Vector with the urls tuple expanded which turns out to be much more useful than the argument splatting itself in my experience.
This is just 1 example of where they've proved useful to me. As you use julia you'll run across more.
It's mostly there to aid in designing api's that feel natural to use.

Why no immutable arrays in scala standard library?

Scala has all sorts sorts of immutable sequences like List, Vector,etc. I have been surprised to find no implementation of immutable indexed sequence backed by a simple array (Vector seems way too complicated for my needs).
Is there a design reason for this? I could not find a good explanation on the mailing list.
Do you have a recommendation for an immutable indexed sequence that has close to the same performances as an array? I am considering scalaz's ImmutableArray, but it has some issues with scala trunk for example.
Thank you
You could cast your array into a sequence.
val s: Seq[Int] = Array(1,2,3,4)
The array will be implicitly converted to a WrappedArray. And as the type is Seq, update operations will no longer be available.
So, let's first make a distinction between interface and class. The interface is an API design, while the class is the implementation of such API.
The interfaces in Scala have the same name and different package to distinguish with regards to immutability: Seq, immutable.Seq, mutable.Seq.
The classes, on the other hand, usually don't share a name. A List is an immutable sequence, while a ListBuffer is a mutable sequence. There are exceptions, like HashSet, but that's just a coincidence with regards to implementation.
Now, and Array is not part of Scala's collection, being a Java class, but its wrapper WrappedArray shows clearly where it would show up: as a mutable class.
The interface implemented by WrappedArray is IndexedSeq, which exists are both mutable and immutable traits.
The immutable.IndexedSeq has a few implementing classes, including the WrappedString. The general use class implementing it, however, is the Vector. That class occupies the same position an Array class would occupy in the mutable side.
Now, there's no more complexity in using a Vector than using an Array, so I don't know why you call it complicated.
Perhaps you think it does too much internally, in which case you'd be wrong. All well designed immutable classes are persistent, because using an immutable collection means creating new copies of it, so they have to be optimized for that, which is exactly what Vector does.
Mostly because there are no arrays whatsoever in Scala. What you're seeing is java's arrays pimped with a few methods that help them fit into the collection API.
Anything else wouldn't be an array, with it's unique property of not suffering type erasure, or the broken variance. It would just be another type with indexes and values. Scala does have that, it's called IndexedSeq, and if you need to pass it as an array to some 3rd party API then you can just use .toArray
Scala 2.13 has added ArraySeq, which is an immutable sequence backed by an array.
Scala 3 now has IArray, an Immutable Array.
It is implemented as an Opaque Type Alias, with no runtime overhead.
The point of the scala Array class is to provide a mechanism to access the abilities of Java arrays (but without Java's awful design decision of allowing arrays to be covariant within its type system). Java arrays are mutable, hence so are those in the scala standard library.
Suppose there were also another class immutable.Array in the library but that the compiler were also to use a Java array as the underlying structure (for efficiency/speed). The following code would then compile and run:
val i = immutable.Array("Hello")
i.asInstanceOf[Array[String]](0) = "Goodbye"
println( i(0) ) //I thought i was immutable :-(
That is, the array would really be mutable.
The problem with Arrays is that they have a fixed size. There is no operation to add an element to an array, or remove one from it.
You can keep an array that you guess will be long enough as a backing store, "wasting" the memory you're not using, keep track of the last used index, and copy to a larger array if you need the extra space. That copying is O(N) obviously.
Changing a single element is also O(N) as you will need to copy over the entire array. There is no structural sharing, which is the lynchpin of performant functional datastructures.
You could also allocate an extra array for the "overflowing" elements, and somehow keep track of your arrays. At that point you're on your way of re-inventing Vector.
In short, due to their unsuitablility for structural sharing, immutable facades for arrays have terrible runtime performance characteristics for most common operations like adding an element, removing an element, and changing an element.
That only leaves the use-case of a fixed size fixed content data-carrier, and that use-case is relatively rare. Most uses better served with List, Stream or Vector
You can simply use Array[T].toIndexSeq to convert Array[T] to ArraySeq[T], which is of type immutable.IndexedSeq[T].
(after Scala 2.13.0)
scala> val array = Array(0, 1, 2)
array: Array[Int] = Array(0, 1, 2)
scala> array.toIndexedSeq
res0: IndexedSeq[Int] = ArraySeq(0, 1, 2)

Resources