The snippets are under the CC-BY-SA license.

Creative Commons Attribution-ShareAlike 3.0

Logo

Programming-Idioms.org

  • The snippets are under the CC-BY-SA license.
  • Please consider keeping a bookmark
  • (instead of printing)
Scala
1
Print a literal string on standard output
println("Hello, World!")
2
Loop to execute some code a constant number of times
(0 until 10).foreach( _ => println("Hello"))
Alternative implementation:
println("Hello\n"*10)
3
Like a function which doesn't return any value, thus has only side effects (e.g. Print to standard output)
def doSomething(name: String): Unit = {
  println(s"My job here is done. Goodbye ${name}")
}
4
Create a function which returns the square of an integer
def square(x:Int): Int = x*x
5
Declare a container type for two floating-point numbers x and y
case class Point(x: Float, y: Float)
6
Do something with each item x of the list (or array) items, regardless indexes.
items.foreach{doSomething(_)}
Alternative implementation:
items.foreach(doSomething)
Alternative implementation:
for {
  x <- items
} doSomething(x)
7
Print each index i with its value x from an array-like collection items
val items = List("a", "b", "c")
items.zipWithIndex.foreach{ case (item, index) => 
  println(s"$index => $item")
}
8
Create a new map object x, and provide some (key, value) pairs as initial content.
val x = Map("a" -> 1, "b" -> 2, "c" -> 3)
9
The structure must be recursive because left child and right child are binary trees too. A node has access to children nodes, but not to its parent.
case class BinaryTree[T <: Ordered[T]](
	value: T,
	left: Option[BinaryTree[T]],
	right: Option[BinaryTree[T]]
)
Alternative implementation:
sealed trait Tree[T <: Ordered[T]]:
  def search(x: T): Boolean
final case class Nil[T <: Ordered[T]]() extends Tree[T]:
  override def search(x: T): Boolean = false
final case class Node[T <: Ordered[T]](
    item: T,
    left: Tree[T],
    right: Tree[T]
) extends Tree[T]:
  override def search(other: T): Boolean =
    item compare other match
      case 0          => true
      case n if n < 0 => left.search(other)
      case n if n > 0 => right.search(other)
10
Generate a random permutation of the elements of list x
val shuffled = Random.shuffle(x)
11
The list x must be non-empty.
val x = List(1, 2, 3, 4)
x.apply(Random.nextInt(x.size))
12
Check if the list contains the value x.
list is an iterable finite container.
list.contains(x)
13
Access each key k with its value x from an associative array mymap, and print them.
val x = Map("a" -> 1, "b" -> 2, "c" -> 3)
x.foreach{ case (key, value) => println(s"$key => $value")}
Alternative implementation:
mymap.foreach { case (k, x) => println(s"$k => $x") }
14
Pick a random number greater than or equals to a, strictly inferior to b. Precondition : a < b.
def randomDraw(min: Double, max: Double): Double = {
  val range = max - min
  (random.doubleValue * range) + min
}
15
Pick a random integer greater than or equals to a, inferior or equals to b. Precondition : a < b.
a + Random.nextInt(b + 1)
17
The structure must be recursive. A node may have zero or more children. A node has access to its children nodes, but not to its parent.
case class Node[T](value: T, children: List[Node[T]] = Nil)
19
Reverse the order of the elements of the list x.
This may reverse "in-place" and destroy the original ordering.
x = x.reverse
20
Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.
def search[T](m: Iterable[Iterable[T]], x: T): Option[(Int, Int)] = {
  for ((row, i) <- m.view.zipWithIndex; (column, j) <- row.view.zipWithIndex if column == x)
    return Some((i, j))
  None
}
21
Swap the values of the variables a and b
val tmp = a
a = b
b = tmp

22
Extract the integer value i from its string representation s (in radix 10)
s.toInt
24
Declare a new string s and initialize it with the literal value "ネコ" (which means "cat" in japanese)
val s = "ネコ"
26
Declare and initialize a matrix x having m rows and n columns, containing real numbers.
val x = Array.ofDim[Double](m,n)
28
Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.
case class S(x: Int)
val items = List(S(3), S(4), S(2))
items.sortBy( item: S => item.x )
Alternative implementation:
items.sortBy(_.x)
29
Remove i-th item from list items.
This will alter the original list or return a new list, depending on which is more idiomatic.
Note that in most languages, the smallest valid value for i is 0.
val without = {
  val (left, right) = items.splitAt(i)
  left ++ right.drop(1)
}
31
Create the recursive function f which returns the factorial of the non-negative integer i, calculated from f(i-1)
def f(i: Int): Int =
  if (i > 1){
    i * f(i-1) 
  } else{
    1
  }
32
Create function exp which calculates (fast) the value x power n.
x and n are non-negative integers.
def exp(x: Int, n: Int): Int {
  if(n == 0) {
    1
  } else if(n == 1) {
    x
  } else if(n%2 == 0) {
    exp(x*x, n/2)
  } else {
    x * exp(x*x, (n-1)/2)
  }
}
34
Declare and initialize a set x containing unique objects of type T.
val x = Set[T]()
37
Transform a function that takes multiple arguments into a function for which some of the arguments are preset.
def add(x: Int, y: Int) = x + y
def add5 = add(5, _)
val seven = add5(2)
Alternative implementation:
def add(x: Int)(y: Int) = x + y
val add5 = add(5)_
38
Find substring t consisting in characters i (included) to j (excluded) of string s.
Character indices start at 0 unless specified otherwise.
Make sure that multibyte characters are properly handled.
val t = s.substring(i, j)
39
Set the boolean ok to true if the string word is contained in string s as a substring, or to false otherwise.
val ok = s.contains(word)
41
Create string t containing the same characters as string s, in reverse order.
Original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.
s.reverse
45
Sleep for 5 seconds in current thread, before proceeding with the next instructions.
Thread.sleep(5000)
46
Create the string t consisting of the 5 first characters of the string s.
Make sure that multibyte characters are properly handled.
val t = s.take(5)
48
Assign to variable s a string literal consisting in several lines of text, including newlines.
val s = """line 1
line 2
line 3"""
Alternative implementation:
val s = """line 1
          |line 2
          |line 3""".stripMargin
49
Build list chunks consisting in substrings of the string s, separated by one or more space characters.
val chunks = s.split(" ")
50
Write a loop that has no end clause.
while(true){
  println(3)
}
51
Determine whether the map m contains an entry for the key k
m.contains(k)
52
Determine whether the map m contains an entry with the value v, for some key.
m.valuesIterator.contains(v)
53
Concatenate elements of string list x joined by the separator ", " to create a single string y.
val y = x.mkString(",")
54
Calculate the sum s of the integer list or array x.
val s = x.sum()
55
Create the string representation s (in radix 10) of the integer value i.
val s = i.toString
57
Create the list y containing the items from the list x that satisfy the predicate p. Respect the original ordering. Don't modify x in-place.
val y = x.filter(p)
58
Create the string lines from the content of the file with filename f.
val lines = Source.fromFile(filename).getLines().mkString("\n")
59
Print the message "x is negative" to standard error (stderr), with integer x value substitution (e.g. "-2 is negative").
System.err.println(s"$x is negative")
71
Basic implementation of the Echo program: Print all arguments except the program name, separated by space, followed by newline.
The idiom demonstrates how to skip the first argument if necessary, concatenate arguments as strings, append newline and print it to stdout.
println(args.mkString(" "))
76
Create the string s of integer x written in base 2.

E.g. 13 -> "1101"
val s = x.toString(2)
78
Execute a block once, then execute it again as long as boolean condition c is true.
do {
  someThing()
  someOtherThing()
} while (c)
96
Set the boolean b to true if string s starts with prefix prefix, false otherwise.
val b = s.startsWith(prefix)
97
Set boolean b to true if string s ends with string suffix, false otherwise.
val b = s.endsWith(suffix)
100
Sort elements of array-like collection items, using a comparator c.
val c: Ordering[Int] = Ordering.Int
val sortedItems = items.sorted(c)

// Or using implicits:

val sortedItems = items.sorted
101
Make an HTTP request with method GET to the URL u, then store the body of the response in the string s.
val s = scala.io.Source.fromURL(u).getLines().mkString("\n")
103
Read from the file data.xml and write its contents into the object x.
Assume the XML data is suitable for the type of x.
val xml = XML.loadFile("data.xml")
110
Set the boolean blank to true if the string s is empty, or null, or contains only whitespace ; false otherwise.
val blank = Option(s).forall(_.trim.isEmpty)
112
Print each key k with its value x from an associative array mymap, in ascending order of k.
SortedMap.from(mymap).foreach{ case (k, x) => println(s"$k => $x") }
114
Set boolean b to true if objects x and y contain the same values, recursively comparing all referenced elements in x and y.
Tell if the code correctly handles recursive types.
case class A(a: Int, b: Float, c: String)
val x = A(1,2.2f,"hello")
val y = A(1,2.2f,"hello")

b = x == y 
117
Set n to the number of elements of the list x.
val n = x.size
118
Create the set y from the list x.
x may contain duplicates. y is unordered and has no repeated values.
val y = x.toSet
119
Remove duplicates from the list x.
Explain if the original order is preserved.
x = x.distinct
120
Read an integer value from the standard input into the variable n
val n = Try(StdIn.readInt())
122
Create an enumerated type Suit with 4 possible values SPADES, HEARTS, DIAMONDS, CLUBS.
sealed trait Suit
case object Spades extends Suit
case object Hearts extends Suit
case object Diamonds extends Suit
case object Clubs extends Suit
126
Write a function foo that returns a string and a boolean value.
def foo(): (String, Boolean) = ("bar", true)
131
Execute f1 if condition c1 is true, or else f2 if condition c2 is true, or else f3 if condition c3 is true.
Don't evaluate a condition when a previous condition was true.
true match {
  case _ if c1 => f1()
  case _ if c2 => f2()
  case _ if c3 => f3()
}
Alternative implementation:
if (c1) {
  f1()
} else if (c2) {
  f2()
} else if (c3) {
  f3()
}
134
Declare and initialize a new list items, containing 3 elements a, b, c.
val items = List(a, b, c)
136
Remove all occurrences of the value x from list items.
This will alter the original list or return a new list, depending on which is more idiomatic.
items.filter(_ != x)
137
Set the boolean b to true if the string s contains only characters in the range '0'..'9', false otherwise.
def onlyDigits(s: String) = s.forall(_.isDigit) 
140
Delete from map m the entry having key k.

Explain what happens if k is not an existing key in m.
m - k
Alternative implementation:
m -= k
142
Assign to string s the hexadecimal representation (base 16) of integer x.

E.g. 999 -> "3e7"
val s = x.toString(16)
150
Remove the last character from the string p, if this character is a forward slash /
p.stripSuffix("/")
153
Create the string t as the concatenation of the string s and the integer i.
val t = s + i
157
Initialize a constant planet with string value "Earth".
val planet = "Earth"
161
Multiply all the elements of the list elements by a constant c
elements.map(_ * c)
163
Print all the list elements, two by two, assuming list length is even.
for (pair <- list.grouped(2))
  println(s"(${pair(0)}, ${pair(1)})")
165
Assign to the variable x the last element of the list items.
val x = items.last
166
Create the list ab containing all the elements of the list a, followed by all the elements of the list b.
val ab = a ++ b
Alternative implementation:
val ab = a ::: b
169
Assign to the integer n the number of characters of the string s.
Make sure that multibyte characters are properly handled.
n can be different from the number of bytes of s.
val n = s.length()
170
Set n to the number of elements stored in mymap.

This is not always equal to the map capacity.
val n = mymap.size
173
Number will be formatted with a comma separator between every group of thousands.
"%,d".format(n)
182
Output the source of the program.
object Quine extends App {
  val s = 
    """object Quine extends App {
      |  val s = 
      |    ""%2$s%1$s%2$s""
      |  print(s.stripMargin.format(s, "\""))
      |}"""
  print(s.stripMargin.format(s, "\""))
}
186
Exit a program cleanly indicating no error to OS
sys.exit(0)
189
Produce a new list y containing the result of the function T applied to all elements e of the list x that match the predicate P.
val y = x.collect { case e if P(e) => T(e) }
205
Read an environment variable with the name "FOO" and assign it to the string variable foo. If it does not exist or if the system does not support environment variables, assign a value of "none".
val foo = sys.env.getOrElse("FOO", "none")
224
Insert the element x at the beginning of the list items.
val newList = x :: items
252
Assign to the variable x the string value "a" if calling the function condition returns true, or the value "b" otherwise.
x = if (condition()) "a" else "b"
Alternative implementation:
x = if condition() then "a" else "b"