Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Roc
https://www.roc-lang.org/tutorial
Admin
Roc is a fast, friendly, functional programming language designed for building robust,
...
Tokens:
6,180
Snippets:
86
Trust Score:
8.2
Update:
1 week ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Start the Roc REPL Source: https://www.roc-lang.org/tutorial Starts the Roc REPL for evaluating expressions and definitions without creating a file. ```bash roc repl ``` -------------------------------- ### Desugared version of `?` operator Source: https://www.roc-lang.org/tutorial Shows the desugared version of the `?` operator example. It explicitly matches each `Try` and returns the `Err` if present. ```roc increment_first = |strings| { first_str = match strings.first() { Ok(val) => val Err(err) => return Err(err) } first_num = match I64.from_str(first_str) { Ok(val) => val Err(err) => return Err(err) } Ok(first_num + 1) } ``` -------------------------------- ### Use return statement in function Source: https://www.roc-lang.org/tutorial Example of using the return keyword to immediately return from a function. If digits is empty, the function returns 0. Statements or expressions after a return in a block may trigger a warning because they will not be executed. ```roc digits_to_num = |digits| { if digits.is_empty() { return 0 } # ...the rest of the function would go here } ``` -------------------------------- ### Use `Try.ok_or` to provide a fallback Source: https://www.roc-lang.org/tutorial Uses the `Try.ok_or` method to get the value inside the `Ok` tag or a fallback value if the `Try` is `Err`. This is a concise alternative to a `match` expression. ```roc number = numbers.first().ok_or(0) ``` -------------------------------- ### Implement digits_to_num with fold Source: https://www.roc-lang.org/tutorial Functional-style implementation of digits_to_num using fold. The fold starts with an accumulator of 0 and applies the function to each digit, multiplying the accumulator by 10 and adding the digit. ```roc digits_to_num = |digits| digits.fold(0, |num, digit| (num * 10) + digit) ``` -------------------------------- ### Block expression with statements and final expression Source: https://www.roc-lang.org/tutorial Example of a block expression. The block ends with an expression (inner_constant.abs()) and the entire block evaluates to that expression. Statements before the final expression are executed, and the block can be assigned to a constant. ```roc answer = { foo = 43 inner_constant = foo - 1 echo!("Inner constant: ${inner_constant.to_str()}") inner_constant.abs() } ``` -------------------------------- ### Hello, World in Roc Source: https://www.roc-lang.org/tutorial Create a new file named main.roc with this Roc program, then run it with `roc main.roc`. The program prints "Hello, World!" and returns Ok({}). The expected output is shown. If you don't provide a path, `roc` defaults to "main.roc". ```roc main! = |_args| { echo!("Hello, World!") Ok({}) } ``` ```bash roc main.roc ``` ```text Hello, World! ``` -------------------------------- ### Define the main! entrypoint Source: https://www.roc-lang.org/tutorial Defines the program entrypoint. The code inside the curly braces runs when executing `roc main.roc`. ```roc main! = |_args| { echo!("Hello, World!") Ok({}) } ``` -------------------------------- ### Create a list Source: https://www.roc-lang.org/tutorial Create a list of strings. Lists are homogeneous, so all elements must have compatible types. ```roc animals = ["bird", "crab", "lizard"] ``` -------------------------------- ### Create list with tags Source: https://www.roc-lang.org/tutorial Use tags to create a list with elements of different types. Each element is wrapped in a tag, making the list homogeneous. ```roc birds_or_numbers = [Bird("eagle"), Number(1)] ``` -------------------------------- ### Use `?` postfix operator for early return Source: https://www.roc-lang.org/tutorial Uses the `?` postfix operator to early-return an `Err` from a `Try`. If the `Try` is `Ok`, it evaluates to its value; otherwise, it returns the `Err`. ```roc increment_first = |strings| { first_str = strings.first()? first_num = I64.from_str(first_str)? Ok(first_num + 1) } ``` -------------------------------- ### Roc app header with basic-cli platform Source: https://www.roc-lang.org/tutorial Header for a Roc application that explicitly selects the basic-cli platform. The header specifies the entrypoint `main!` and the platform dependency URL. Headerless apps use the built-in Echo Platform instead. ```roc app [main!] { pf: platform "https://github.com/roc-lang/basic-cli/releases/download/0.22.2/9zUBxb1LtXYVc4eR4hAtd1WQDwBYDhM6HQdZz1UFCm2m.tar.zst" } ``` -------------------------------- ### Expected output from piped Roc REPL input Source: https://www.roc-lang.org/tutorial Expected output from piping the previous PowerShell command to the Roc REPL. ```text assigned `x` 4.0 ``` -------------------------------- ### Define `Try.ok_or` with underscore pattern Source: https://www.roc-lang.org/tutorial Shows the definition of the `Try.ok_or` method. It uses an underscore pattern `Err(_)` to ignore the error value and return the fallback. ```roc ok_or = |try, fallback| match try { Ok(val) => val Err(_) => fallback } ``` -------------------------------- ### Test digits_to_num with expect statements Source: https://www.roc-lang.org/tutorial Use these expect statements to test the digits_to_num function. When run with `roc test`, each expect passes if the expression evaluates to True and fails if it evaluates to False. The file does not need a main! function or an app header. ```roc expect digits_to_num([1, 2, 3]) == 123 expect digits_to_num([4, 2]) == 42 expect digits_to_num([7]) == 7 ``` -------------------------------- ### Update record with spread syntax Source: https://www.roc-lang.org/tutorial Update a record by creating a new one with some fields changed. The spread syntax ..record copies the existing fields, and the name field is overridden. ```roc new_record = { ..record, name: "New Name" } ``` -------------------------------- ### Match on `List.first` result with `Ok` and `Err` Source: https://www.roc-lang.org/tutorial Shows how to use a `match` expression with `Ok` and `Err` tags to handle the result of `List.first`. The `Err` branch matches the `ListWasEmpty` tag, which is returned when the list is empty. ```roc numbers = [1, 2 ,3 ] number = match numbers.first() { Ok(first) => first + 1 Err(ListWasEmpty) => 0 } ``` -------------------------------- ### Create record with if expression Source: https://www.roc-lang.org/tutorial Create a record with fields name and has_name, choosing different values based on a condition. The record type is inferred from the branches. ```roc record = if str.is_empty() { { name: "n/a", has_name: Bool.False } } else { { name: str, has_name: Bool.True } } ``` -------------------------------- ### Pipe multiple lines to Roc REPL in PowerShell Source: https://www.roc-lang.org/tutorial Sends multiple input lines to the Roc REPL in PowerShell using an array. In piped mode, only evaluation output is printed to stdout; prompts, banner, and goodbye are omitted. ```powershell @("x = 1 + 1", "x * 2") | roc repl ``` -------------------------------- ### Implement digits_to_num with for loop and var Source: https://www.roc-lang.org/tutorial Imperative-style implementation of digits_to_num using a for loop and a reassignable var. The var $num is reassigned inside the loop, and the function returns the final value. Vars begin with $ to distinguish them from constants. ```roc digits_to_num = |digits| { var $num = 0 for digit in digits { $num = ($num * 10) + digit } $num } ``` -------------------------------- ### Define and use a name in the Roc REPL Source: https://www.roc-lang.org/tutorial Defines a name and uses it in a later input within the Roc REPL. ```roc x = 1 + 1 x * 2 ``` -------------------------------- ### Pipe multiple lines to Roc REPL in Unix shells Source: https://www.roc-lang.org/tutorial Sends multiple input lines to the Roc REPL in Unix shells using printf. In piped mode, only evaluation output is printed to stdout; prompts, banner, and goodbye are omitted. ```bash printf 'x = 1 + 1\nx * 2\n' | roc repl ``` -------------------------------- ### Match on `Try` with multiple `Err` branches Source: https://www.roc-lang.org/tutorial Demonstrates matching on a `Try` value that can be either `Ok` or `Err` with different error tags. The `Err` branches distinguish between `ListWasEmpty` from `List.first` and `BadNumStr` from `I64.from_str`. ```roc num_or_err = if numbers.is_empty() { I64.from_str("1") } else { numbers.first() } answer = match num_or_err { Ok(num) => num + 1 Err(ListWasEmpty) => 0 Err(BadNumStr) => -1 } ``` -------------------------------- ### Pattern match on list Source: https://www.roc-lang.org/tutorial Pattern match on a list to extract elements and compute a value. The default branch _ => is required to handle all possible list lengths and contents. ```roc points = match animals { ["bird", "crab", "lizard"] => 10 # exact match ["bird", "crab", ..] => 5 # partial match ["bird", ..] => 1 # partial match [first, second, "lizard", ..] => count_points(first, second) _ => 0 # default } ``` -------------------------------- ### if expression with simple branches Source: https://www.roc-lang.org/tutorial Use an if expression to choose between two values based on a condition. The condition is a function call, and the branches are simple expressions. ```roc name = if str.is_empty() "n/a" else str ``` -------------------------------- ### Pattern match on tags Source: https://www.roc-lang.org/tutorial Pattern match on tags to access their contents. The pattern [Bird(bird), Number(num)] binds the inner values, and the default branch handles other cases. ```roc label = match birds_or_numbers { [Bird(bird), Number(num)] => "${bird} number ${num.to_str()}" _ => "" # default } ``` -------------------------------- ### Evaluate an expression in the Roc REPL Source: https://www.roc-lang.org/tutorial Evaluates an expression in the Roc REPL. ```roc 1 + 1 ``` -------------------------------- ### List with incompatible types (compile error) Source: https://www.roc-lang.org/tutorial This code will cause a compile error because the list contains both a string and a number, which are incompatible types. ```roc animals = ["eagle", 1] ``` -------------------------------- ### expect statement in Roc Source: https://www.roc-lang.org/tutorial Use `expect` inside a block to assert an assumption that should always hold. During `roc test` or debug builds, a failing `expect` behaves like a `crash`; in `--opt=speed` builds, `expect` statements are skipped entirely. These are development-time checks, not production assertions. ```roc digits_to_num = |digits| { if digits.is_empty() { return 0 } # From here on, we assume digits is nonempty! expect !digits.is_empty() # ...the rest of the function would go here } ``` -------------------------------- ### Define a constant Source: https://www.roc-lang.org/tutorial Defines a constant called `name`. Constants should not be reassigned or shadowed; doing so produces a compile-time warning with exit code 2. ```roc name = "Rocco" ``` -------------------------------- ### Destructure record Source: https://www.roc-lang.org/tutorial Destructure a record to bring its fields into scope as constants. The fields name and has_name become available as variables. ```roc { name, has_name } = record ``` -------------------------------- ### Use block expression inside echo! Source: https://www.roc-lang.org/tutorial A block expression used as an argument to echo!. The block contains a var declaration and a for loop, then ends with an expression that converts the total to a string. This shows that blocks can incorporate statements into expressions. ```roc echo!({ var $total = 0 for number in 1..=10 { $total = $total + number } $total.to_str() }) ``` -------------------------------- ### Interpolate an integer with to_str Source: https://www.roc-lang.org/tutorial Uses string interpolation with an integer by calling `to_str` because Roc does not automatically convert other types in ordinary string interpolation. ```roc echo!("Number of things: ${thing_count.to_str()}") ``` -------------------------------- ### Interpolate a complex expression Source: https://www.roc-lang.org/tutorial Shows that any expression can be placed inside a string interpolation, though extracting complex expressions into a constant is often more readable. ```roc echo!("Answer: ${((numerator / denominator) + 1).negate().to_str()}") ``` -------------------------------- ### if expression with block branches Source: https://www.roc-lang.org/tutorial Use an if expression with block branches to make the code more readable. The blocks contain the values for each branch. ```roc name = if str.is_empty() { "n/a" } else { str } ``` -------------------------------- ### dbg statement in Roc Source: https://www.roc-lang.org/tutorial Use `dbg` for printline debugging in Roc. It works in pure functions and prints to stderr in command-line applications, but may appear in the browser console for WebAssembly builds. Due to compile-time evaluation, there is no guarantee whether a given `dbg` runs at compile time or runtime. ```roc main! = |_args| { x = 5 dbg x # dbg(x) works too Ok({}) } ``` -------------------------------- ### crash statement in Roc Source: https://www.roc-lang.org/tutorial Use `crash` to terminate the application when an unrecoverable condition occurs, such as an empty list. The platform determines what happens after a crash; it may recover or terminate immediately. Avoid using `crash` for recoverable errors, which should be handled with normal types like `Try`. ```roc digits_to_num = |digits| { if digits.is_empty() { crash "Expected a nonempty list." } # ...the rest of the function would go here } ``` -------------------------------- ### Reassigning var inside for_each! causes error Source: https://www.roc-lang.org/tutorial This code is an error because $count is declared with var in the outer scope and then reassigned inside a different function (the closure passed to for_each!). The error indicates that vars can only be reassigned inside the function where they were declared. ```roc var $count = 0 things.for_each!(|thing| { $count = $count + 1 # other logic goes here }) ```