Start learning free

LESSON 4 OF 70 · PROJECTS: COMMAND-LINE TOOLS

cat v4 in Scala: Concatenate Files with Nested Loops

Practice Read the full explanation

The real cat command can take many files as arguments and prints them one after another. Build that behavior. Given a list of "files" where each file is itself a list of lines, flatten all lines in order and join them with newlines.

A file can be empty (it adds no lines), and the list can hold no files at all; the result is then an empty string.

Function signature:

def concatCat(allLines: List[List[String]]): String

Example:

Input: allLines = [["hello", "world"], ["foo", "bar", "baz"]]

Output: "hello\nworld\nfoo\nbar\nbaz"

When printed:
hello
world
foo
bar
baz

Build a flat buffer of String with a nested loop, preserving order. Then return flat.mkString("\n").

val flat = scala.collection.mutable.ArrayBuffer[String]()
for (fileLines <- allLines) {
    for (line <- fileLines) {
        flat += line
    }
}
return flat.mkString("\n")


The full solution:
class Solution {
    def concatCat(allLines: List[List[String]]): String = {
        val flat = scala.collection.mutable.ArrayBuffer[String]()
        for (fileLines <- allLines) {
            for (line <- fileLines) {
                flat += line
            }
        }
        return flat.mkString("\n")
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Cat V4 in Scala, explained

    Problem overview

    The real cat command takes several files and prints them one after another. This version models that with a function, concatCat, that receives allLines: List[List[String]]: a list of "files", where each file is itself a list of lines. The function flattens all the lines in order and joins them with newlines.

    For [["hello", "world"], ["foo", "bar", "baz"]] the result is "hello\nworld\nfoo\nbar\nbaz". A file can be empty, in which case it adds no lines, and the list can hold no files at all, in which case the result is an empty string.

    Approach

    The input has two levels: files, and lines inside each file. The output has one level: a single sequence of lines. The job is to flatten the two levels into one, keeping the order, and then use mkString("\n") to join, as in the first version.

    The flattening is a nested loop. The outer loop visits the files in order. For each file, the inner loop visits its lines in order and appends each to one growing buffer. Because the files are visited in order and each file's lines are visited in order, the buffer ends up with every line in the order cat would print them.

    An empty file never enters its inner loop, so it adds nothing. An empty list of files never enters the outer loop, so the buffer stays empty and mkString on an empty buffer returns "".

    Join once at the end, over the flat buffer. That is what keeps the separators correct: newlines appear only between lines of the final sequence, however the lines were spread over files.

    Step by step

    1. Create the buffer. flat is an empty scala.collection.mutable.ArrayBuffer[String](), a list that can grow. It will hold every line of every file, with no lists inside it.
    2. Loop over the files with for (fileLines <- allLines). Each fileLines is a List[String].
    3. Loop over that file's lines with for (line <- fileLines), nested inside the first loop.
    4. Add the line to the buffer with flat += line.
    5. Join after both loops and return flat.mkString("\n").

    The solution in Scala

    class Solution {
        def concatCat(allLines: List[List[String]]): String = {
            val flat = scala.collection.mutable.ArrayBuffer[String]()
            for (fileLines <- allLines) {
                for (line <- fileLines) {
                    flat += line
                }
            }
            return flat.mkString("\n")
        }
    }
    

    Details worth knowing:

    • The buffer is a val, yet it grows. val means the name flat can't be pointed at another object, but an ArrayBuffer is a mutable collection, so += changes it in place. A plain List can't change, which is why the lesson uses a buffer.
    • The full name scala.collection.mutable.ArrayBuffer is written out because Scala's default collections are the immutable ones. A bare ArrayBuffer would need an import.
    • Inside the buffer's [String] the element type is fixed, so adding a List[String] instead of a String would not compile.
    • The loops use for (x <- collection), which runs its body once per element and gives the element a name.

    A shorter way to write it

    A list of lists has a flatten method that does the two nested loops for you:

    allLines.flatten.mkString("\n")
    

    With [["hello", "world"], ["foo", "bar", "baz"]] it gives "hello\nworld\nfoo\nbar\nbaz", and with an empty list of files it gives "". The lesson builds the buffer by hand so that the structure of the nested loop is explicit.

    Edge cases and common mistakes

    • No files. List() gives "".
    • Only empty files. List(List(), List()) also gives "", because no line ever reaches the buffer.
    • An empty file between others. List(List(), List("x"), List()) gives "x". The empty files contribute nothing, not even a newline.
    • Joining each file first. Calling mkString("\n") on every file and then joining those strings with another newline puts an empty string into the outer join for each empty file. List(List("a"), List(), List("b")) gives "a\n\nb" that way, with a blank row that no file contained. Flatten first and join once.
    • Forgetting the order. The result must keep the files in the order given, each file's lines in their own order. Sorting or reversing anywhere breaks that.
    • A trailing newline. Appending "\n" after every line would leave an extra one at the end. Joining with mkString avoids it.

    Testing

    InputResult
    List(List("hello", "world"), List("foo", "bar", "baz"))"hello\nworld\nfoo\nbar\nbaz"
    List(List(), List("x"), List())"x"
    List(List(), List())""
    List()""
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free