Start learning free

LESSON 5 OF 70 · PROJECTS: COMMAND-LINE TOOLS

head v1 in Scala: The First 10 Lines with take

Practice Read the full explanation

Build a tiny version of the Unix head command. Given a list of lines, return the first 10 lines joined by newline characters (\n). If the input has fewer than 10 lines, return all of them. If there are no lines at all, return the empty string.

Function signature:

def head(lines: List[String]): String

Example:

Input: lines = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]

Output: "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"

When printed:
a
b
c
d
e
f
g
h
i
j

Use take to grab the first 10 lines — take safely caps at the list length when it is shorter than 10. Then call mkString("\n") on the result.

Compute val end = math.min(10, lines.size), then call lines.take(end).

The full solution:
class Solution {
    def head(lines: List[String]): String = {
        val end = math.min(10, lines.size)
        lines.take(end).mkString("\n")
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Head V1 in Scala, explained

    Problem overview

    The Unix head command prints the start of its input. This first version is a function, head, that takes a List[String] and returns the first 10 lines joined by newline characters (\n). If there are fewer than 10 lines, it returns all of them, and for no lines at all it returns the empty string.

    For a list of the 13 letters "a" to "m", the result is "a\nb\nc\nd\ne\nf\ng\nh\ni\nj". Lines k, l and m are dropped.

    Approach

    There are two jobs: choose which lines to keep, then join them. The joining is mkString("\n"), which puts a newline between each pair of neighbours and none after the last. The choosing is the part specific to head.

    A list method, take(k), keeps the first k items. The lesson computes how many to ask for before calling it: the smaller of 10 and the number of lines. With 13 lines that number is 10. With 3 lines it is 3, and with 0 lines it is 0. So the call never asks for lines that aren't there, and the empty list needs no special case.

    For the three lines "a", "b", "c", take(10) gives List(a, b, c), and take(0) gives List(). In Scala take never fails when it is asked for more than the list holds, so the math.min is a clear statement of intent more than a safety net.

    Step by step

    1. Compute the count. val end = math.min(10, lines.size) is the smaller of 10 and the number of lines: 10 for 13 lines, 3 for 3 lines, 0 for none.
    2. Take and join. lines.take(end) keeps the first end lines, and mkString("\n") glues them. This is the last expression of the method, so it is the value the method returns and no return is needed.

    The solution in Scala

    class Solution {
        def head(lines: List[String]): String = {
            val end = math.min(10, lines.size)
            lines.take(end).mkString("\n")
        }
    }
    

    Details worth knowing:

    • math.min is a function in the scala.math package, which Scala makes available as math without an import. It works on Int, Long, Double and the other number types.
    • lines.size counts the items. On a List it walks the whole list, which is fine for a few lines.
    • take returns a new list and leaves lines unchanged. A List is immutable, so every such method gives a new value.
    • The method body is a block, and a block's value is its last expression. That is why lines.take(end).mkString("\n") sits on its own line without return. Writing return in front would behave the same.

    Edge cases and common mistakes

    • Fewer than 10 lines. List("a", "b", "c") gives "a\nb\nc": all three lines, with no padding to reach 10.
    • Exactly 10 and 11 lines. Both give the same ten lines, "a\nb\nc\nd\ne\nf\ng\nh\ni\nj", because for 11 lines the eleventh is cut and for 10 nothing is.
    • No lines. List() gives "", since take(0) of an empty list is empty and mkString on it returns an empty string.
    • Counting from the wrong place. take(10) keeps 10 lines, indices 0 to 9. Using take(9) or take(11) is the usual off-by-one.
    • A trailing newline. Joining with mkString("\n") leaves nothing after the last kept line. Appending a newline per line in a loop would leave one.

    Testing

    InputResult
    the 13 letters "a" to "m""a\nb\nc\nd\ne\nf\ng\nh\ni\nj"
    the first 11 of those letters"a\nb\nc\nd\ne\nf\ng\nh\ni\nj"
    List("a", "b", "c")"a\nb\nc"
    List()""

    The next version builds on this one.

    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free