Basics of Scala

Description of the page content

Conversion of old BASIC programs to Scala in order to learn the basics of this language.

Tags:

3D Plot

/*
3D Plot

Original version in BASIC:
  Creative Computing (Morristown, New Jersey, USA), ca. 1980.

This version in Scala:
  Copyright (c) 2023, Marcos Cruz (programandala.net)
  SPDX-License-Identifier: Fair

Written in 2023-08, 2023-09.

Last modified: 20231103T2352+0100.
*/

def home() =
  print("\u001B[H")

def clear() =
  print("\u001B[2J")
  home()

def showCredits() =
  println("3D Plot\n")
  println("Original version in BASIC:")
  println("    Creative computing (Morristown, New Jersey, USA), ca. 1980.\n")
  println("This version in Scala:")
  println("    Copyright (c) 2023, Marcos Cruz (programandala.net)")
  println("    SPDX-License-Identifier: Fair\n")
  println("Press any key to start the program.")
  io.StdIn.readLine("")


def a(z: Double): Double =
  30 * math.exp(-z * z / 100)

def draw() =

  val width = 56
  val space = ' '
  val dot = '*'
  var line = new Array[Char](width)

  var l = 0
  var y1 = 0
  var z = 0

  var x = -30.0
  while x <= 30 do
    line = Array.fill(width){space}
    l = 0
    y1 = 5 * (math.sqrt(900 - x * x) / 5).toInt
    for y <- y1 to -y1 by -5 do
      z = (25 + a(math.sqrt(x * x + (y * y)))-0.7 * y).toInt
      if z > l then
        l = z
        line(z) = dot
    for pos <- 0 until width do
      print(line(pos))
    println()
    x += 1.5

@main def main() =
  clear()
  showCredits()
  clear()
  draw()

Bagels

/*
Bagels

Original version in BASIC:
  D. Resek, P. Rowe, 1978.
  Creative Computing (Morristown, New Jersey, USA), 1978.

This version in Scala:
  Copyright (c) 2023, Marcos Cruz (programandala.net)
  SPDX-License-Identifier: Fair

Written in 2023-09/10, 2023-11.

Last modified: 20231104T0112+0100.
*/

// Move the cursor to the home position.
def home() =
  print("\u001B[H")

// Clear the screen and move the cursor to the home position.
def clear() =
  print("\u001B[2J")
  home()

// Print the given prompt and wait until the user enters an empty string.
def pressEnter(prompt : String) =
  var ok = false
  while !ok do
    ok = io.StdIn.readLine(prompt) == ""
  end while

def printTitle() =
  clear()
  println("Bagels")
  println("Number guessing game\n")

// Clear the screen, display the credits and wait for a keypress.
def printCredits() =
  printTitle()
  println("Original source unknown but suspected to be:")
  println("    Lawrence Hall of Science, U.C. Berkely.\n")
  println("Original version in BASIC:")
  println("    D. Resek, P. Rowe, 1978.")
  println("    Creative computing (Morristown, New Jersey, USA), 1978.\n")
  println("This version in Scala:")
  println("    Copyright (c) 2023, Marcos Cruz (programandala.net)")
  println("    SPDX-License-Identifier: Fair\n")
  pressEnter("Press Enter to read the instructions. ")

// Clear the screen, print the instructions and wait for a keypress.
def printInstructions() =
  printTitle()
  println("I am thinking of a three-digit number that has no two digits the same.")
  println("Try to guess it and I will give you clues as follows:\n")
  println("   PICO   - one digit correct but in the wrong position")
  println("   FERMI  - one digit correct and in the right position")
  println("   BAGELS - no digits correct")
  pressEnter("\nPress Enter to start. ")

val Digits = 3

// Return three random digits.
def random() : Array[Int]  =
  val randomDigit = new Array[Int](Digits)
  var digit = 0
  for i <- 0 until Digits do
    var validDigit = false
    while !validDigit do
      digit = util.Random.nextInt(10)
      validDigit = !randomDigit.contains(digit)
    end while
    randomDigit(i) = digit
  end for
  randomDigit

// Prints the given prompt, waits until the user enters a valid integer and
// returns it.
def getNumber(prompt : String) : Int =
  var number = 0
  var ok = false
  while !ok do
    try
      number = io.StdIn.readLine(prompt).trim.toInt
      ok = true
    catch
    case _ => println("Invalid number.")
  end while
  number

// Prompts the user to enter a command and returns it trimmed.
def getString(prompt : String = "> ") : String =
  io.StdIn.readLine(prompt).trim

// Return `true` if any of the elements of the given string is repeated;
// otherwise return `false`.
def isAnyRepeated(s: String) : Boolean =
  s.size != s.toSet.size

def containsOnlyDigits(s: String) : Boolean =
  var ok = true
  s.foreach(char => ok = ok && char.toChar.isDigit)
  ok

// Print the given prompt and get a three-digit number from the user.
def input(prompt : String) : Array[Int]  =
  val ASCII_0 = 48
  val userDigit = new Array[Int](Digits)
  var inputString = ""
  var done = false
  while !done do
    inputString = getString(prompt)
    if inputString.size != Digits then
      println(s"Remember it's a ${Digits}-digit number.")
    else
      if containsOnlyDigits(inputString) then
        if isAnyRepeated(inputString) then
          println("Remember my number has no two digits the same.")
        else
          done = true
        end if
      else
        println("What?")
      end if
    end if
  end while
  for i <- 0 until Digits do
    userDigit(i) = inputString(i).asDigit
  end for
  userDigit

// Return `true` if the given string is "yes" or a synonym.
def isYes(answer : String) : Boolean  =
  Array("ok", "yeah", "yes", "y").contains(answer)

// Return `true` if the given string is "no" or a synonym.
def isNo(answer : String) : Boolean  =
  Array("no", "nope", "n").contains(answer)

// Print the given prompt, wait until the user enters a valid yes/no
// string, and return `true` for "yes" or `false` for "no".
def yes(prompt : String) : Boolean  =
  var answer = ""
  while !(isYes(answer) || isNo(answer)) do
    answer = getString(prompt)
  isYes(answer)

// Init and run the game loop.
def play() =
  val TRIES = 20
  var score = 0
  var playing = true
  var userNumber = new Array[Int](Digits)
  while playing do
    clear()
    var computerNumber = random()
    println("O.K.  I have a number in mind.")
    var fermi = 0
    var pico  = 0
    var guess = 1 // counter
    while fermi != Digits && guess <= TRIES do
      userNumber = input(s"Guess #${guess}: ")
      fermi = 0
      pico = 0
      for i <- 0 until Digits do
        for j <- 0 until Digits do
          if computerNumber(i) == userNumber(j) then
            if i == j then
              fermi += 1
            else
              pico += 1
            end if
          end if
        end for
      end for
      print("PICO ".repeat(pico))
      print("FERMI ".repeat(fermi))
      if pico + fermi == 0 then
        print("BAGELS")
      end if
      println()
      guess += 1
    end while
    if fermi == Digits then
      println("You got it!!!")
      score += 1
    else
      println("Oh well.")
      print(s"That's $TRIES guesses.  My number was ")
      computerNumber.foreach(print)
      println(".")
    end if
    if !yes("Play again? ") then
      playing = false
    end if
  end while // play loop
  if score != 0 then
    println(s"A ${score}-point bagels, buff!!")
  end if
  println("Hope you had fun.  Bye.")

@main def main() =
  printCredits()
  printInstructions()
  play()

Bunny

/*
Bunny

Original version in BASIC:
  Creative Computing (Morristown, New Jersey, USA), 1978.

This version in Scala:
  Copyright (c) 2023, Marcos Cruz (programandala.net)
  SPDX-License-Identifier: Fair

Written in 2023-08, 2023-09.

Last modified: 20231209T2009+0100.
*/

// Move the cursor to the top left position of the terminal.
def home() =
  print("\u001B[H")

// Clear the terminal and move the cursor to the top left position.
def clearScreen() =
  print("\u001B[2J")
  home()

// Clear the screen, print the credits and wait for the Enter key.
def printCredits() =
  clearScreen()
  println("Bunny\n")
  println("Original version in BASIC:")
  println("    Creative Computing (Morristown, New Jersey, USA), 1978.\n")
  println("This version in Scala:")
  println("    Copyright (c) 2023, Marcos Cruz (programandala.net)")
  println("    SPDX-License-Identifier: Fair\n")
  println("Press Enter to start the program.")
  io.StdIn.readLine("")

val Width = 53
var line = new Array[Int](Width) // buffer

// Clear the line buffer with spaces.
def clearLine() =
  var column = 0
  for column <- 0 until Width do
    line(column) = ' '.toInt

val letter = Array('B', 'U', 'N', 'N', 'Y')
var letters = letter.length

val EOL : Int = -1 // end of line identifier
var data : Array[Int] = Array(
  1, 2, EOL, 0, 2, 45, 50, EOL, 0, 5, 43, 52, EOL, 0, 7, 41, 52, EOL,
  1, 9, 37, 50, EOL, 2, 11, 36, 50, EOL, 3, 13, 34, 49, EOL, 4, 14,
  32, 48, EOL, 5, 15, 31, 47, EOL, 6, 16, 30, 45, EOL, 7, 17, 29, 44,
  EOL, 8, 19, 28, 43, EOL, 9, 20, 27, 41, EOL, 10, 21, 26, 40, EOL,
  11, 22, 25, 38, EOL, 12, 22, 24, 36, EOL, 13, 34, EOL, 14, 33, EOL,
  15, 31, EOL, 17, 29, EOL, 18, 27, EOL, 19, 26, EOL, 16, 28, EOL,
  13, 30, EOL, 11, 31, EOL, 10, 32, EOL, 8, 33, EOL, 7, 34, EOL, 6,
  13, 16, 34, EOL, 5, 12, 16, 35, EOL, 4, 12, 16, 35, EOL, 3, 12, 15,
  35, EOL, 2, 35, EOL, 1, 35, EOL, 2, 34, EOL, 3, 34, EOL, 4, 33,
  EOL, 6, 33, EOL, 10, 32, 34, 34, EOL, 14, 17, 19, 25, 28, 31, 35,
  35, EOL, 15, 19, 23, 30, 36, 36, EOL, 14, 18, 21, 21, 24, 30, 37, 37,
  EOL, 13, 18, 23, 29, 33, 38, EOL, 12, 29, 31, 33, EOL, 11, 13, 17,
  17, 19, 19, 22, 22, 24, 31, EOL, 10, 11, 17, 18, 22, 22, 24, 24, 29,
  29, EOL, 22, 23, 26, 29, EOL, 27, 29, EOL, 28, 29, EOL)

def printLine() =
  for i <- line do
    print(i.toChar)
  println()

var dataIndex = 0

def datum() =
  dataIndex += 1
  data(dataIndex - 1)

// Draw the graphic out of `data` and `letter`.
def draw() =
  clearScreen()
  clearLine()
  while dataIndex < data.length do
    val firstColumn = datum()
    if firstColumn == EOL then
      printLine()
      clearLine()
    else
      val lastColumn = datum()
      for column <- firstColumn to lastColumn do
        line(column) = letter(column % letters).toInt

@main def main() =
  printCredits()
  draw()

Diamond

/*
Diamond

Original version in BASIC:
  Example included in Vintage BASIC 1.0.3.
  http://www.vintage-basic.net

This version in Scala:
  Copyright (c) 2023, Marcos Cruz (programandala.net)
  SPDX-License-Identifier: Fair

Written on 2023-08-25.

Last modified: 20231103T2352+0100.
*/

val lines = 17

@main def diamond() =

  var i = 1
  var j = 1

  while i <= lines / 2 + 1 do
    j = 1
    while j <= (lines + 1) / 2 - i + 1 do
      print(" ")
      j += 1
    j = 1
    while j <= i * 2 - 1 do
      print("*")
      j += 1
    println()
    i += 1

  i = 1
  while i <= lines / 2 do
    j = 1
    while j <= i + 1 do
      print(" ")
      j += 1
    j = 1
    while j <= ((lines + 1) / 2 - i) * 2 - 1 do
      print("*")
      j += 1
    println()
    i += 1

Math

/*
Math

Original version in BASIC:
  Example included in Vintage BASIC 1.0.3.
  http://www.vintage-basic.net

This version in Scala:
  Copyright (c) 2023, Marcos Cruz (programandala.net)
  SPDX-License-Identifier: Fair

Written on 2023-08-26.

Last modified: 20231103T2352+0100.
*/

@main def main() =

  print("Enter a number: ")
  var n : Float =
  try
    io.StdIn.readFloat()
  catch
    case e: NumberFormatException => 0.0

  print(s"ABS($n) = math.abs($n) = "); println(math.abs(n))
  print(s"ATN($n) = math.atan($n) = "); println(math.atan(n))
  print(s"COS($n) = math.cos($n) = "); println(math.cos(n))
  print(s"EXP($n) = math.exp($n) = "); println(math.exp(n))
  print(s"INT($n) = $n.toInt = "); println(n.toInt)
  print(s"LOG($n) = math.log($n) = "); println(math.log(n))
  print(s"SGN($n) = math.signum($n) = "); println(math.signum(n))
  print(s"SQR($n) = math.sqrt($n) = "); println(math.sqrt(n))
  print(s"TAN($n) = math.tan($n) = "); println(math.tan(n))

Mugwump

// Mugwump
//
// Original version in BASIC:
//   Written by Bud Valenti's students of Project SOLO (Pittsburg, Pennsylvania, USA).
//   Slightly modified by Bob Albrecht of People's Computer Company.
//   Published by Creative Computing (Morristown, New Jersey, USA), 1978.
//   - https://www.atariarchives.org/basicgames/showpage.php?page=114
//   - http://vintage-basic.net/games.html
//
// This version in Scala:
//   Copyright (c) 2023, Marcos Cruz (programandala.net)
//   SPDX-License-Identifier: Fair
//
// Written in 2023-09, 2023-11.
//
// Last modified: 20231104T0113+0100.

val GridSize = 10
val Turns = 10
val Mugwumps = 4

class Mugwump :
  var hidden : Boolean = true
  var x : Int = 0
  var y : Int = 0
  def reveal() =
    hidden = false
  def init() =
    hidden = true
    x = util.Random.nextInt(GridSize)
    y = util.Random.nextInt(GridSize)

// Moves the cursor to the top left position of the terminal.
def home() =
  print("\u001B[H")

// Clears the terminal and moves the cursor to the top left position.
def clear() =
  print("\u001B[2J")
  home()

// Prompts the user to enter a command and returns it trimmed.
def command(prompt : String = "> ") : String =
  io.StdIn.readLine(prompt).trim

// Prints the given prompt, waits until the user enters a valid integer and
// returns it.
def getNumber(prompt : String) : Int =
  var number = 0
  var ok = false
  while !ok do
    try
      number = command(prompt).toInt
      ok = true
    catch
    case _ => println("Invalid number.")
  number

// Prints the given prompt and waits until the user enters an empty string.
def pressEnter(prompt : String) =
  var ok = false
  while !ok do
    ok = io.StdIn.readLine(prompt) == ""

// Returns `true` if the given string is "yes" or a synonym.
def isYes(answer : String) : Boolean =
  answer.toLowerCase match
    case "ok" => true
    case "yeah" => true
    case "yes" => true
    case "y" => true
    case _ => false

// Returns `true` if the given string is "no" or a synonym.
def isNo(answer : String) : Boolean =
  answer.toLowerCase match
    case "no" => true
    case "nope" => true
    case "n" => true
    case _ => false

// Prints the given prompt, waits until the user enters a valid yes/no
// string, and returns `true` for "yes" or `false` for "no".
def yes(prompt : String) : Boolean =
  var answer : String = ""
  while !(isYes(answer) || isNo(answer)) do
    answer = command(prompt)
  isYes(answer)

// Clears the screen, prints the credits and asks the user to press enter.
def printCredits() =
  clear()
  println("Mugwump\n")
  println("Original version in BASIC:")
  println("    Written by Bud Valenti's students of Project SOLO (Pittsburg, Pennsylvania, USA).")
  println("    Slightly modified by Bob Albrecht of People's Computer Company.")
  println("    Published by Creative Computing (Morristown, New Jersey, USA), 1978.")
  println("    - https://www.atariarchives.org/basicgames/showpage.php?page=114")
  println("    - http://vintage-basic.net/games.html\n")
  println("This version in Scala:")
  println("    Copyright (c) 2023, Marcos Cruz (programandala.net)")
  println("    SPDX-License-Identifier: Fair\n")
  pressEnter("Press Enter to read the instructions. ")

// Clears the screen, prints the instructions and asks the user to press enter.
def printInstructions() =
  clear()
  println("Mugwump\n")
  println("The object of this game is to find four mugwumps")
  println("hidden on a 10 by 10 grid.  Homebase is position 0,0.")
  println("Any guess you make must be two numbers with each")
  println("number between 0 and 9, inclusive.  First number")
  println("is distance to right of homebase and second number")
  println("is distance above homebase.\n")
  print(s"You get ${Turns} tries.  After each try, you will see\n")
  println("how far you are from each mugwump.\n")
  pressEnter("Press Enter to start. ")

// Prints the given prompt, then waits until the user enters a valid coord and
// returns it.
def getCoord(prompt : String) : Int =
  var coord : Int = 0
  var right = false
  while !right do
    coord = getNumber(prompt)
    if coord < 0 || coord >= GridSize then
      print(s"Invalid value ${coord}: not in range [0, ${GridSize - 1}].\n")
    else
      right = true
  coord

// Returns `true` if the given mugwump is hidden in the given coords.
def isHere(m : Mugwump, x : Int, y : Int) : Boolean =
  m.hidden && m.x == x && m.y == y

// Returns the distance between the given mugwump and the given coords.
def distance(m : Mugwump, x : Int, y : Int) : Int =
  math.sqrt(math.pow((m.x - x), 2) + math.pow((m.y - y), 2)).toInt

// If the given number is greater than 1, this method returns a plural ending
// (default: "s"); otherwise it returns a singular ending (default: an empty
// string).
def plural(n : Int, plural : String = "s", singular : String = "") : String =
  if n > 1 then plural else singular

// Prints the mugwumps found in the given coordinates and returns the count.
def foundAt(mugwump : Array[Mugwump], x : Int, y : Int) : Int =
  var found : Int = 0
  for m <- 0 until Mugwumps do
    if isHere(mugwump(m), x, y) then
      mugwump(m).reveal()
      found += 1
      print(s"You have found mugwump ${m}!\n")
    end if
  end for
  found

// Runs the game.
def play() =

  var found : Int = 0 // counter
  var turn : Int = 0 // counter
  var m : Int = 0
  var x : Int = 0
  var y : Int = 0
  var gameOver = false

  val mugwump = new Array[Mugwump](Mugwumps)
  for m <- 0 until Mugwumps do
    mugwump(m) = new Mugwump

  while !gameOver do // game

    clear()

    for m <- 0 until Mugwumps do
      mugwump(m).init()

    found = 0
    turn = 0
    while turn < Turns && found < Mugwumps do
      turn += 1
      print(s"Turn number ${turn}\n\n")
      print(s"What is your guess (in range [0, ${GridSize - 1}])?\n")
      x = getCoord("Distance right of homebase (x-axis): ")
      y = getCoord("Distance above homebase (y-axis): ")
      print(s"\nYour guess is ($x, $y).\n")
      found += foundAt(mugwump, x, y)
      if found < Mugwumps then
        for m <- 0 until Mugwumps do
          if mugwump(m).hidden then
            print(s"You are ${distance(mugwump(m), x, y)} units from mugwump ${m}.\n")
          end if
        end for
        println("")
      end if
    end while // turns

    if found == Mugwumps then
      print(s"\nYou got them all in ${turn} turn${plural(turn)}!\n\n")
      println("That was fun! let's play again…")
      println("Four more mugwumps are now in hiding.")
    else
      print(s"\nSorry, that's ${Turns} tr${plural(Turns, "ies", "y")}.\n\n")
      println("Here is where they're hiding:")
      for m <- 0 until Mugwumps do
        if mugwump(m).hidden then
          print(s"Mugwump $m is at (${mugwump(m).x}, ${mugwump(m).y}).\n")
        end if
      end for
    end if

    println("")
    gameOver = !yes("Do you want to play again? ")

  end while // game

@main def main() =
  printCredits()
  printInstructions()
  play()

Russian Roulette

/*
Russian Roulette

Original version in BASIC:
  Creative Computing (Morristown, New Jersey, USA), ca. 1980.

This version in Scala:
  Copyright (c) 2023, Marcos Cruz (programandala.net)
  SPDX-License-Identifier: Fair

Written in 2023-09.

Last modified: 20231103T2352+0100.
*/

// Move the cursor to the top left position of the terminal.
def home() =
  print("\u001B[H")

// Clear the terminal and move the cursor to the top left position.
def clear() =
  print("\u001B[2J")
  home()

// Prompts the user to enter a command and returns it trimmed.
def command(prompt : String = "> ") : String =
  io.StdIn.readLine(prompt).trim

// Prints the given prompt and waits until the user enters an empty string.
def pressEnter(prompt : String) =
  var ok = false
  while !ok do
    ok = io.StdIn.readLine(prompt) == ""

def pressEnterToStart() =
  pressEnter("Press Enter to start. ")

def printCredits() =
  clear()
  println("Russian Roulette\n")
  println("Original version in BASIC:")
  println("    Creative Computing (Morristown, New Jersey, USA), ca. 1980.\n")
  println("This version in Scala:")
  println("    Copyright (c) 2023, Marcos Cruz (programandala.net)")
  println("    SPDX-License-Identifier: Fair\n")
  pressEnterToStart()

def printCommands() =
  println("Type 'f' to spin chamber and pull trigger.")
  println("Type 'g' to give up, and play again.")
  println("Type 'q' to quit.")

def printInstructions() =
  clear()
  println("Here is a revolver.")
  printCommands()
  println()

def play() =
  var gameOver = false
  while !gameOver do // game loop
    printInstructions()
    var times = 0
    var playing = true
    while playing do // play loop
       command() match
          case "f"  => // fire
            if util.Random.nextInt(100) > 83 then
              println("Bang! You're dead!")
              println("Condolences will be sent to your relatives.")
              playing = false
            else
              times += 1
              if times > 10 then
                println("You win!")
                println("Let someone else blow his brains out.")
                playing = false
              else
                println("Click.")
          case "g"  => // give up
            println("Chicken!")
            playing = false
          case "q"  => // quit
            playing = false
            gameOver = true
          case _ =>
            println("Wrong action.")
            printCommands()
    end while // play loop
    pressEnterToStart()
  end while // game loop

@main def main() =
  printCredits()
  play()
  println("Bye!")

Sine Wave

/*
Sine Wave

Original version in BASIC:
  Creative Computing (Morristown, New Jersey, USA), ca. 1980.

This version in Scala:
  Copyright (c) 2023, Marcos Cruz (programandala.net)
  SPDX-License-Identifier: Fair

Written in 2023-08, 2023-09.

Last modified: 20231103T2352+0100.
*/

def home() =
  print("\u001B[H")

def clear() =
  print("\u001B[2J")
  home()

val order = Array("first", "second")

var word = Array("", "")

def getWords() =
  clear()
  for w <- Seq(0, 1) do
    word(w) = io.StdIn.readLine(s"Enter the ${order(w)} word: ")

def showCredits() =
  clear()
  println("Sine Wave\n")
  println("Original version in BASIC:")
  println("    Creative Computing (Morristown, New Jersey, USA), ca. 1980.\n")
  println("This version in Scala:")
  println("    Copyright (c) 2023, Marcos Cruz (programandala.net)")
  println("    SPDX-License-Identifier: Fair\n")
  println("Press Enter to start the program.")
  io.StdIn.readLine("")

def draw() =
  clear()
  var even = true
  var angle = 0.0
  while angle <= 40 do
    print(" " * (26 + 25 * math.sin(angle)).toInt)
    println(word(if even then 0 else 1))
    even = !even
    angle += 0.25

@main def main() =
  showCredits()
  getWords()
  draw()

Strings

// Strings
//
// Original version in BASIC:
//   Example included in Vintage BASIC 1.0.3.
//   http://www.vintage-basic.net
//
// This version in Scala:
//   Copyright (c) 2023, Marcos Cruz (programandala.net)
//   SPDX-License-Identifier: Fair
//
// Written in 2023-09-28/29.
//
// Last modified: 20231209T2008+0100.

// Prompts the user to enter a command and returns it trimmed.
def readString(prompt : String = "") : String =
  scala.io.StdIn.readLine(prompt).trim

// Prompts the user to enter an integer and returns it.
def readInteger(prompt : String = "") : Int =
  var integer = 0
  var ok = false
  while !ok do
    try
      integer = readString(prompt).toInt
      ok = true
    catch
    case _ => println("That wasn't a valid integer.")
  integer

@main def main() =

  val s = readString("Enter a string: ")
  val n = readInteger("Enter an integer: ")

  print(s"ASC(\"$s\") --> ")
  print(s"\"$s\"(0).toChar.toInt --> ")
  println(s"${s(0).toChar.toInt}")

  print(s"CHR$$($n) --> ")
  print(s"$n.toChar --> ")
  println(s"'${n.toChar}'")

  print(s"LEFT$$(\"$s\", $n) --> ")
  print(s"\"$s\".substring(0, $n.min(\"$s\".size)) --> ")
  println(s"\"${s.substring(0, n.min(s.size))}\"")

  print(s"MID$$(\"$s\", $n) --> ")
  print(s"\"$s\".substring(($n - 1).min(\"$s\".size)) --> ")
  println(s"\"${s.substring((n - 1).min(s.size))}\"")

  print(s"MID$$(\"$s\", $n, 3) --> ")
  print(s"\"$s\".substring(($n - 1).min(\"$s\".size), ($n - 1 + 3).min(\"$s\".size)) --> ")
  println(s"\"${s.substring((n - 1).min(s.size), (n - 1 + 3).min(s.size))}\"")

  print(s"RIGHT$$(\"$s\", $n) --> ")
  print(s"\"$s\".substring((\"$s\".size - $n).max(0)) --> ")
  println(s"\"${s.substring((s.size - n).max(0))}\"")

  print(s"LEN(\"$s\") --> ")
  print(s"\"$s\".size --> ")
  println(s.size)

  print(s"VAL(\"$s\") --> ")
  print(s"try \"$s\".trim.toFloat catch case _ => (0.0) --> ")
  println(try s.trim.toFloat catch case _ => (0.0))

  print(s"STR$$($n) --> ")
  print(s"$n.toString --> ")
  println(s"\"${n.toString}\"")

  print(s"SPC($n) --> ")
  print(s"\" \".repeat($n) --> ")
  println(s"\"${" ".repeat(n)}\"")

Related pages

Basics off
Metaproject about the "Basics of…" projects.
Basics of 8th
Conversion of old BASIC programs to 8th in order to learn the basics of this language.
Basics of Ada
Conversion of old BASIC programs to Ada in order to learn the basics of this language.
Basics of Arturo
Conversion of old BASIC programs to Arturo in order to learn the basics of this language.
Basics of C#
Conversion of old BASIC programs to C# in order to learn the basics of this language.
Basics of C3
Conversion of old BASIC programs to C3 in order to learn the basics of this language.
Basics of Chapel
Conversion of old BASIC programs to Chapel in order to learn the basics of this language.
Basics of Clojure
Conversion of old BASIC programs to Clojure in order to learn the basics of this language.
Basics of Crystal
Conversion of old BASIC programs to Crystal in order to learn the basics of this language.
Basics of D
Conversion of old BASIC programs to D in order to learn the basics of this language.
Basics of Elixir
Conversion of old BASIC programs to Elixir in order to learn the basics of this language.
Basics of F#
Conversion of old BASIC programs to F# in order to learn the basics of this language.
Basics of Factor
Conversion of old BASIC programs to Factor in order to learn the basics of this language.
Basics of FreeBASIC
Conversion of old BASIC programs to FreeBASIC in order to learn the basics of this language.
Basics of Gleam
Conversion of old BASIC programs to Gleam in order to learn the basics of this language.
Basics of Go
Conversion of old BASIC programs to Go in order to learn the basics of this language.
Basics of Hare
Conversion of old BASIC programs to Hare in order to learn the basics of this language.
Basics of Haxe
Conversion of old BASIC programs to Haxe in order to learn the basics of this language.
Basics of Icon
Conversion of old BASIC programs to Icon in order to learn the basics of this language.
Basics of Io
Conversion of old BASIC programs to Io in order to learn the basics of this language.
Basics of Janet
Conversion of old BASIC programs to Janet in order to learn the basics of this language.
Basics of Julia
Conversion of old BASIC programs to Julia in order to learn the basics of this language.
Basics of Kotlin
Conversion of old BASIC programs to Kotlin in order to learn the basics of this language.
Basics of Lobster
Conversion of old BASIC programs to Lobster in order to learn the basics of this language.
Basics of Lua
Conversion of old BASIC programs to Lua in order to learn the basics of this language.
Basics of Nature
Conversion of old BASIC programs to Nature in order to learn the basics of this language.
Basics of Neat
Conversion of old BASIC programs to Neat in order to learn the basics of this language.
Basics of Neko
Conversion of old BASIC programs to Neko in order to learn the basics of this language.
Basics of Nelua
Conversion of old BASIC programs to Nelua in order to learn the basics of this language.
Basics of Nim
Conversion of old BASIC programs to Nim in order to learn the basics of this language.
Basics of Nit
Conversion of old BASIC programs to Nit in order to learn the basics of this language.
Basics of Oberon-07
Conversion of old BASIC programs to Oberon-07 in order to learn the basics of this language.
Basics of OCaml
Conversion of old BASIC programs to OCaml in order to learn the basics of this language.
Basics of Odin
Conversion of old BASIC programs to Odin in order to learn the basics of this language.
Basics of Pike
Conversion of old BASIC programs to Pike in order to learn the basics of this language.
Basics of Pony
Conversion of old BASIC programs to Pony in order to learn the basics of this language.
Basics of Python
Conversion of old BASIC programs to Python in order to learn the basics of this language.
Basics of Racket
Conversion of old BASIC programs to Racket in order to learn the basics of this language.
Basics of Raku
Conversion of old BASIC programs to Raku in order to learn the basics of this language.
Basics of Retro
Conversion of old BASIC programs to Retro in order to learn the basics of this language.
Basics of Rexx
Conversion of old BASIC programs to Rexx in order to learn the basics of this language.
Basics of Ring
Conversion of old BASIC programs to Ring in order to learn the basics of this language.
Basics of Rust
Conversion of old BASIC programs to Rust in order to learn the basics of this language.
Basics of Scheme
Conversion of old BASIC programs to Scheme in order to learn the basics of this language.
Basics of Styx
Conversion of old BASIC programs to Styx in order to learn the basics of this language.
Basics of Swift
Conversion of old BASIC programs to Swift in order to learn the basics of this language.
Basics of V
Conversion of old BASIC programs to V in order to learn the basics of this language.
Basics of Vala
Conversion of old BASIC programs to Vala in order to learn the basics of this language.
Basics of Zig
Conversion of old BASIC programs to Zig in order to learn the basics of this language.

External related links