for loop

How to iterate over a Map in Kotlin (for loop)

Kotlin FAQ: How do I iterate over a Map in Kotlin?

Solution: Here’s an example of how to iterate over a Map in Kotlin using a for loop:

val map = mapOf("a" to 1, "b" to 2, "c" to 3)

for ((k,v) in map) {
    println("value of $k is $v")
}

Inside that for loop the variables k and v refer to the Map keys and values, respectively.

Example in the Kotlin REPL

Here’s what that looks like in the Kotlin REPL:

Scala for/yield examples (for-loop and yield examples)

I just found some notes from when I first began working with Scala, and I was working with the yield keyword in for loops. If you haven't worked with something like yield before, it will be helpful to know how it works. Here's a statement of how the yield keyword works in for loops, based on the documentation in the book, Programming in Scala:

How to process every line in a file with a Unix/Linux shell script

Unix/Linux shell script FAQ: How do I write a Unix or Linux shell script where I "do something" for every line in a text file?

Solution: An easy way to process every line in a text file is to use a Unix/Linux while loop in combination with the Linux cat command, like this:

How to use multiple Futures in a Scala for-comprehension

If you want to create multiple Scala Futures and merge their results together to get a result in a for comprehension, the correct approach is to (a) first create the futures, (b) merge their results in a for comprehension, then (c) extract the result using onComplete or a similar technique.

A Linux shell script to rename files with a counter and copy them

As a brief note today, I was recently looking for all Messages/iMessage files that are stored on my Mac, and I used this shell script to copy all of those files — many of which have the same name — into a directory named tmpdir, giving them all new names during the copy process:

count=1
for i in `cat myfiles`
do
    fname=`basename $i`
    cp $i tmpdir/${count}-${fname}
    count=`expr $count + 1`
done

This is a page from my book, Functional Programming, Simplified

How to Enable the Use of Multiple Generators in a ‘for’ Expression

One cool thing about for expressions is that you can use multiple generators inside of them. This lets you do some nice analytics when you have some interesting data relationships.

For instance, suppose you have some data like this: