concept REPL in category functional programming

appears as: REPL, The REPL, REPL
Grokking Functional Programming

This is an excerpt from Manning's book Grokking Functional Programming.

Install 

sbt
 - Scala Build Tool

sbt is a build tool used in the Scala ecosystem. It can be used to create, build and test projects. Visit https://www.scala-sbt.org/download.html to get the instructions of how to install the sbt on your platform.

What about an IDE?

You can also use an IDE! The most beginner-friendly one is IntelliJ IDEA. After installing Java, you can download this IDE from https://www.jetbrains.com/idea/.

The best feature to use with this book would be a Scala Worksheet, which is the IDE version of REPL.

Run it!

In your shell, run the command sbt console. This will start the Scala REPL (Read Evaluate Print Loop). This is the preferred tool to run examples and do exercises in this book. It allows you to write a line of code, press enter and get feedback immediately. Have a look below to get some intuition on how to use this tool:

 

Note:

We recommend using REPL (sbt console) with this book, especially at the beginning, because it works out of the box and you won’t get distracted.

>  def inc(x: Int): Int = x + 1        #A → inc                               #B   inc(2)                              #C → 3   def score(word: String): Int =      #D    word.replaceAll(“a”, “”).length  #E → score                             #F   score(“java”)                       #G → 2   val words = List(“rust”, “java”) → words: List[String]               #H   words.sortBy(score)                 #I → List(“java”, “rust”)

#A  Type code here and press the enter key to execute it immediately. Here we define a function in one line!

#B  The REPL confirms that we defined a function called inc.

#C  We call the function inc and pass 2 as x. REPL prints out the result.

#D  We can define even bigger functions in REPL. When the definition is not complete and you press enter, REPL will wait for more input.

#E  Here’s a two line definition of our scoring function

#A  The REPL confirms that we defined a function called score. This function will be in scope for the duration of the REPL session.

#F  We call the function score and pass "java" as an argument. REPL prints the result: 2.

#G  We can create a new value which contains an immutable list with two words. This one is called words, as confirmed by REPL response.

#H  We now call the sortBy function defined in Scala’s List class.

#I  sortBy function takes another function as a parameter. It uses it to sort the contents of the list and it returns a new, sorted list as a result, which is printed by the REPL. The words list remains unchanged.