Start learning free

LESSON 609 OF 677 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v1 — First 10 Lines

Practice

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