StdIn
The StdIn module provides functions for reading from standard input. This is typically used for interactive programs, command-line tools that accept piped input, and scripts that need user input.
All Stdin functions are nullary (zero-argument) and are automatically
invoked when referenced. You don't need to call them with ().
For example, use StdIn.read-line instead of StdIn.read-line().
Reading Input
match StdIn.read-line
| Ok line -> println "You entered: ${line}"
| Err e -> println "Error reading input: ${e}"
# Read piped input: echo "hello world" | ./my-program
match StdIn.read-all
| Ok content -> println "Received: ${content}"
| Err e -> println "Error: ${e}"
match StdIn.read-bytes
| Ok bytes -> println "Read ${length bytes} bytes"
| Err e -> println "Error: ${e}"
Usage Examples
Interactive Prompt
Create a simple interactive prompt that reads user input:
prompt = fn(message) =>
print message
match StdIn.read-line
| Ok input -> input
| Err _ -> ""
name = prompt "Enter your name: "
println "Hello, ${name}!"
Reading Multiple Lines
Read lines until the user enters an empty line:
read-lines = fn(acc) =>
match StdIn.read-line
| Ok "" -> acc
| Ok line -> read-lines (acc ++ [line])
| Err _ -> acc
println "Enter lines (empty line to finish):"
lines = read-lines []
println "You entered ${length lines} lines"
Processing Piped Input
Process input piped from another command:
# Usage: cat data.txt | ./my-program
match StdIn.read-all
| Ok content ->
lines = String.split content "\n"
non-empty = lines |> filter (fn(l) => String.length l > 0)
println "Processed ${length non-empty} lines"
| Err e ->
Stderr.write-line "Failed to read input: ${e}"
Yes/No Confirmation
Ask the user for confirmation:
confirm = fn(question) =>
print "${question} [y/n]: "
match StdIn.read-line
| Ok "y" -> true
| Ok "Y" -> true
| Ok "yes" -> true
| _ -> false
if confirm "Delete file?" then
println "Deleting..."
else
println "Cancelled"
Password Input
Read sensitive input (note: input will still be visible):
print "Enter password: "
match StdIn.read-line
| Ok password ->
if String.length password < 8 then
println "Password too short"
else
println "Password accepted"
| Err _ ->
println "Failed to read password"