### Install Flix using Nix (Current Shell) Source: https://github.com/flix/book/blob/master/src/getting-started.md Install the Flix package manager for the current shell session using Nix. ```shell nix-shell -p flix ``` -------------------------------- ### Function Type Syntax Examples Source: https://github.com/flix/book/blob/master/src/functions.md Illustrates the syntax for function types based on the number of arguments. ```flix Unit -> Int32 // For nullary functions Int32 -> Int32 // For unary functions (Int32, Int32, ...) -> Int32 // For the rest ``` -------------------------------- ### Install Flix using Nix (Globally) Source: https://github.com/flix/book/blob/master/src/getting-started.md Install the Flix package manager globally on your system using Nix. ```shell nix-env -i flix ``` -------------------------------- ### Building a GET Request with Parameters and Headers Source: https://github.com/flix/book/blob/master/src/http-and-https.md Construct a GET request using HttpRequest.get and chain methods like withQueryParam, withQueryParams, withBearerToken, withHeader, and withTimeout to configure the request. Send the request with Http.send. ```flix use Net.Http use Net.HttpRequest use Net.HttpResponse use Time.Duration.seconds def main(): Unit \ { Http, IO } = let req = HttpRequest.get("https://flix.dev/api/search") |> HttpRequest.withQueryParam("q", "flix programming language") |> HttpRequest.withQueryParams(Map#{ "page" => "1", "per_page" => "25", "sort" => "relevance" }) |> HttpRequest.withBearerToken("ghp_aBcDeFgHiJkLmNoPqRsTuVwXyZ") |> HttpRequest.withHeader("User-Agent", "MyApp/1.0") |> HttpRequest.withTimeout(seconds(5)); match Http.send(req) { case Ok(resp) => println("Status: ${HttpResponse.status(resp)}"); println("Body: ${String.takeLeft(80, HttpResponse.body(resp))}") case Err(err) => println("Error: ${err}") } ``` -------------------------------- ### Execute a Command with Process.exec Source: https://github.com/flix/book/blob/master/src/process.md Demonstrates the basic usage of Process.exec to start an external command and handle its success or failure. ```flix use Sys.Process def main(): Unit \ { Process, IO } = match Process.exec("java", "-version" :: Nil) { case Result.Ok(_) => println("Process started successfully.") case Result.Err(err) => println("Unable to execute process: ${err}") } ``` -------------------------------- ### Creating a Chain with Cons Source: https://github.com/flix/book/blob/master/src/chains-and-vectors.md Example of creating a simple chain using Chain.cons and Chain.empty. ```flix let c = Chain.cons(1, Chain.empty()); println(c) ``` -------------------------------- ### Basic Console I/O Example Source: https://github.com/flix/book/blob/master/src/console.md Demonstrates the simplest usage of the Console effect by printing a prompt, reading user input, and then printing a greeting. ```APIDOC ## Basic Console I/O The simplest use of `Console` is to print a prompt, read input, and respond: ```flix use Sys.Console def main(): Unit \ Console = Console.print("What is your name? "); let name = Console.readln(); Console.println("Hello ${name}!") ``` ``` -------------------------------- ### Example of connect function with valid input Source: https://github.com/flix/book/blob/master/src/applicative-for-yield.md Demonstrates calling the 'connect' function with valid username and password, resulting in a Success containing the created Connection. ```flix connect("luckyluke", "password12356789") ``` -------------------------------- ### Example Usage of Lazy Stream Operations Source: https://github.com/flix/book/blob/master/src/laziness.md Demonstrates creating an infinite stream, mapping a function to its elements, and taking a finite number of results. The output shows the first 10 elements after adding 10 to each starting from 42. ```flix IntStream.from(42) |> IntStream.map(x -> x + 10) |> IntStream.take(10) ``` -------------------------------- ### Test Results Summary Source: https://github.com/flix/book/blob/master/src/build.md Example output from the `test` command, showing the results of executed test cases. ```text Running 1 tests... PASS test01 1,1ms Passed: 1, Failed: 0. Skipped: 0. Elapsed: 3,9ms. ``` -------------------------------- ### String Transformation with Pipeline Source: https://github.com/flix/book/blob/master/src/functions.md A simple example of using the pipeline operator to transform a string to uppercase and print it. ```flix "Hello World" |> String.toUpperCase |> println ``` -------------------------------- ### Seeded Randomness Example Source: https://github.com/flix/book/blob/master/src/random.md Illustrates how to use the `runWithSeed` handler for reproducible random number generation, useful for testing and benchmarks. ```APIDOC ## Seeded Randomness ### Description Demonstrates using `runWithSeed` to ensure reproducible sequences of random numbers. ### Code Example ```flix use Math.Random def main(): Unit \ IO = run { let a = Random.randomFloat64(); let b = Random.randomFloat64(); println("a = ${a}, b = ${b}") } with Random.runWithSeed(42i64) ``` ### Notes Using `runWithSeed` with a fixed seed makes the random number generation deterministic, eliminating the `Random` effect without requiring `IO`. ``` -------------------------------- ### Basic Sleep Example Source: https://github.com/flix/book/blob/master/src/sleep.md Demonstrates the basic usage of the `Sleep` effect to pause the thread for a fixed duration. ```flix use Time.Duration.seconds use Time.Sleep def main(): Unit \ { Sleep, IO } = println("Going to sleep..."); Sleep.sleep(seconds(1)); println("Woke up!") ``` -------------------------------- ### In-Memory Filesystem Operations Source: https://github.com/flix/book/blob/master/src/filesystem.md Demonstrates creating directories, writing files, listing entries, reading content, deleting files, and checking existence using an in-memory filesystem. This handler starts empty and does not access the real filesystem. ```flix use Fs.FileSystem use Time.Clock def main(): Unit \ { Clock, IO } = run { let result = forM ( _ <- FileSystem.mkDirs("/data"); _ <- FileSystem.write(str = "Hello", "/data/hello.txt"); _ <- FileSystem.write(str = "World", "/data/world.txt"); entries <- FileSystem.list("/data"); content <- FileSystem.read("/data/hello.txt"); _ <- FileSystem.delete("/data/hello.txt"); exists <- FileSystem.exists("/data/hello.txt") ) yield (entries, content, exists); match result { case Err(err) => println("Error: ${err}") case Ok((entries, content, exists)) => println("Files in /data:"); foreach (entry <- entries) { println(" ${entry}") }; println("Content: ${content}"); println("Exists after delete: ${exists}") } } with FileSystem.withInMemoryFS ``` -------------------------------- ### Check Java Version Source: https://github.com/flix/book/blob/master/src/getting-started.md Use this command to verify if Java is installed and check its version. Ensure you have Java 21 or newer. ```shell java -version ``` -------------------------------- ### Curried Function Application Example Source: https://github.com/flix/book/blob/master/src/functions.md Demonstrates currying by calling `sum` with one argument, creating a new function `inc` that adds 1. ```flix def sum(x: Int32, y: Int32): Int32 = x + y def main(): Unit \ IO = let inc = sum(1); inc(42) |> println ``` -------------------------------- ### Using Effects with Default Handlers in `main` Source: https://github.com/flix/book/blob/master/src/default-handlers.md This example shows how to use effects like Clock, Env, and Logger in the `main` function without explicit handlers, relying on their default handlers. ```flix use Sys.Env use Time.Clock def main(): Unit \ {Clock, Env, Logger} = let ts = Clock.currentTime(TimeUnit.Milliseconds); let os = Env.getOsName(); Logger.info("UNIX Timestamp: ${ts}"); Logger.info("Operating System: ${os}") ``` -------------------------------- ### Flix Dependency Resolution Output Example Source: https://github.com/flix/book/blob/master/src/packages.md Illustrates the console output during Flix dependency resolution, showing the download and verification of both Flix and Maven packages based on the project's manifest. ```text Found `flix.toml'. Checking dependencies... Resolving Flix dependencies... Downloading `flix/museum.toml` (v1.4.0)... OK. Downloading `flix/museum-entrance.toml` (v1.2.0)... OK. Downloading `flix/museum-giftshop.toml` (v1.1.0)... OK. Downloading `flix/museum-restaurant.toml` (v1.1.0)... OK. Downloading `flix/museum-clerk.toml` (v1.1.0)... OK. Cached `flix/museum-clerk.toml` (v1.1.0). Downloading Flix dependencies... Downloading `flix/museum.fpkg` (v1.4.0)... OK. Downloading `flix/museum-entrance.fpkg` (v1.2.0)... OK. Downloading `flix/museum-giftshop.fpkg` (v1.1.0)... OK. Downloading `flix/museum-restaurant.fpkg` (v1.1.0)... OK. Downloading `flix/museum-clerk.fpkg` (v1.1.0)... OK. Cached `flix/museum-clerk.fpkg` (v1.1.0). Resolving Maven dependencies... Adding `org.apache.commons:commons-lang3' (3.12.0). Running Maven dependency resolver. Dependency resolution completed. ``` -------------------------------- ### Main Function with Env and Exit Effects Source: https://github.com/flix/book/blob/master/src/main.md This example demonstrates a main function that uses the Env and Exit effects to access command-line arguments and control program termination. ```flix use Sys.Env use Sys.Exit def main(): Unit \ {Env, Exit} = let args = Env.getArgs(); match List.head(args) { case None => println("Missing argument."); Exit.exit(1) case Some(a) => println("Hello ${a}!") } ``` -------------------------------- ### Check Neovim Version Source: https://github.com/flix/book/blob/master/src/getting-started.md Verify that your Neovim installation meets the minimum version requirement for the Flix plugin. ```shell nvim --version ``` -------------------------------- ### Confirmed Input Example Source: https://github.com/flix/book/blob/master/src/console.md Illustrates the use of `Console.confirm` to ask a yes/no question, allowing for a default value if the user provides no input. ```APIDOC ## Confirmed Input The `Console.confirm` function asks a yes/no question and returns a `Bool`. You can supply a default value that is used when the user presses Enter without typing anything: ```flix use Sys.Console def main(): Unit \ Console = let proceed = Console.confirm("Deploy to production?", default = true); if (proceed) Console.println("Deploying...") else Console.println("Aborted.") ``` ``` -------------------------------- ### Reading and Writing Array Elements Source: https://github.com/flix/book/blob/master/src/arrays.md Use `Array.get` to read and `Array.put` to write elements at specific indices in an array. This example demonstrates creating an array, populating it, and then retrieving its elements. ```flix region rc { let strings = Array.empty(rc, 2); Array.put("Hello", 0, strings); Array.put("World", 1, strings); let s1 = Array.get(0, strings); let s2 = Array.get(1, strings); println("${s1} ${s2}") } ``` -------------------------------- ### Constructor Overloading with File Objects Source: https://github.com/flix/book/blob/master/src/creating-objects.md Shows how Flix resolves constructors based on the number and types of arguments, using the File class as an example. ```flix import java.io.File def main(): Unit \ IO = let f1 = new File("foo.txt"); let f2 = new File("bar", "foo.txt"); println("Hello World!") ``` -------------------------------- ### Debugging with Source Locations using d""" Source: https://github.com/flix/book/blob/master/src/debugging.md This example shows how to use the `d"""` string interpolator with `dprintln` to automatically include source location information in debug output. ```flix use Debug.dprintln; def sum(x: Int32, y: Int32): Int32 = let result = x + y; dprintln(d"The sum of ${x} and ${y} is ${result}"); result ``` -------------------------------- ### Validated Input Example Source: https://github.com/flix/book/blob/master/src/console.md Shows how `Console.readlnWith` can be used to repeatedly prompt the user until their input satisfies a given validation condition. ```APIDOC ## Validated Input The `Console.readlnWith` function repeatedly prompts the user until the input passes a validator. The validator returns `Ok(value)` on success or `Err(message)` to re-prompt: ```flix use Sys.Console def main(): Unit \ Console = let n = Console.readlnWith("Enter a number (1-10): ", s -> match Int32.fromString(s) { case Some(i) if i >= 1 and i <= 10 => Ok(i) case _ => Err("Please enter a number between 1 and 10.") } ); Console.println("You entered: ${n}") ``` ``` -------------------------------- ### Select from Multiple Channels Source: https://github.com/flix/book/blob/master/src/concurrency.md Use `select` to receive a message from a collection of channels. This example demonstrates receiving from either a 'meow' or 'woof' channel. ```flix def meow(tx: Sender[String]): Unit \ Chan = Channel.send("Meow!", tx) def woof(tx: Sender[String]): Unit \ Chan = Channel.send("Woof!", tx) def main(): Unit \ {Chan, NonDet, IO} = region rc { let (tx1, rx1) = Channel.buffered(1); let (tx2, rx2) = Channel.buffered(1); spawn meow(tx1) @ rc; spawn woof(tx2) @ rc; select { case m <- recv(rx1) => m case m <- recv(rx2) => m } |> println ``` -------------------------------- ### Example of connect function with invalid input Source: https://github.com/flix/book/blob/master/src/applicative-for-yield.md Demonstrates calling the 'connect' function with invalid username and password, resulting in a Failure containing both validation errors. ```flix connect("Lucky Luke", "Ratata") ``` -------------------------------- ### Generating Random Values Example Source: https://github.com/flix/book/blob/master/src/random.md Demonstrates the basic usage of the Random effect to generate a random Float64 and use it in a conditional statement. ```APIDOC ## Generating Random Values ### Description Shows a simple example of using the `Random` effect to generate a random float and make a decision. ### Code Example ```flix use Math.Random def main(): Unit \ { Random, IO } = let flip = Random.randomFloat64() > 0.5; if (flip) println("heads") else println("tails") ``` ### Notes The `Random` effect has a default handler, so it is automatically handled without explicit `runWithIO`. ``` -------------------------------- ### Defining Custom Effects and Handlers in Flix Source: https://github.com/flix/book/blob/master/src/introduction.md Demonstrates how to define and use custom effects and handlers. This example defines `MyPrint` and `MyTime` effects and provides handlers to customize their behavior. ```flix eff MyPrint { def println(s: String): Unit } eff MyTime { def getCurrentHour(): Int32 } def sayGreeting(name: String): Unit \ {MyPrint, MyTime} = { let hour = MyTime.getCurrentHour(); if (hour < 12) MyPrint.println("Good morning, ${name}") else MyPrint.println("Good afternoon, ${name}") } def main(): Unit \ IO = run { (sayGreeting("Mr. Bond, James Bond"): Unit) } with handler MyPrint { def println(s, k) = { println(s); k() } } with handler MyTime { def getCurrentHour(_, k) = k(11) } ``` -------------------------------- ### Multiple Effects and Handlers Example: Ask and Say Source: https://github.com/flix/book/blob/master/src/effects-and-handlers.md Illustrates handling multiple effects, 'Ask' and 'Say', within a single function. It shows how to declare both effects and provide separate handlers for each in the 'main' function. ```flix eff Ask { def ask(): String } eff Say { def say(s: String): Unit } def greeting(): Unit \ {Ask, Say} = let name = Ask.ask(); Say.say("Hello Mr. ${name}") def main(): Unit \ IO = run { greeting() } with handler Ask { def ask(_, resume) = resume("Bond, James Bond") } with handler Say { def say(s, resume) = { println(s); resume() } } ``` -------------------------------- ### Pipelined Function Application Source: https://github.com/flix/book/blob/master/src/functions.md Shows how to chain function applications using the pipeline operator `|>`. This example filters even numbers, squares them, and prints the result. ```flix List.range(1, 100) |> List.filter(x -> x `Int32.mod` 2 == 0) |> List.map(x -> x * x) |> println; ``` -------------------------------- ### Simple Counter Implementation Source: https://github.com/flix/book/blob/master/src/references.md Implements a counter using a reference, with functions to create, get the count, and increment. The `Counter` type includes a region parameter. ```flix enum Counter[r: Region] { case Counter(Ref[Int32, r]) } def newCounter(rc: Region[r]): Counter[r] \ r = Counter.Counter(Ref.fresh(rc, 0)) def getCount(c: Counter[r]): Int32 \ r = let Counter.Counter(l) = c; Ref.get(l) def increment(c: Counter[r]): Unit \ r = let Counter.Counter(l) = c; Ref.put(Ref.get(l) + 1, l) def main(): Unit \ IO = region rc { let c = newCounter(rc); increment(c); increment(c); increment(c); getCount(c) |> println } ``` -------------------------------- ### Example of Stratified Negation in Flix Source: https://github.com/flix/book/blob/master/src/stratified-negation.md Demonstrates stratified negation by defining a rule to find movies where the director does not star. This example requires no external setup beyond the Flix environment. ```flix def main(): Unit \ IO = let movies = #{ Movie("The Hateful Eight"). Movie("Interstellar"). }; let actors = #{ StarringIn("The Hateful Eight", "Samuel L. Jackson"). StarringIn("The Hateful Eight", "Kurt Russel"). StarringIn("The Hateful Eight", "Quentin Tarantino"). StarringIn("Interstellar", "Matthew McConaughey"). StarringIn("Interstellar", "Anne Hathaway"). }; let directors = #{ DirectedBy("The Hateful Eight", "Quentin Tarantino"). DirectedBy("Interstellar", "Christopher Nolan"). }; let rule = #{ MovieWithoutDirector(title) :- Movie(title), DirectedBy(title, name), not StarringIn(title, name). }; query movies, actors, directors, rule select title from MovieWithoutDirector(title) |> println ``` -------------------------------- ### Create Directories Source: https://github.com/flix/book/blob/master/src/filesystem.md Shows how to create directories using `mkDirs` for nested directories and `mkTempDir` for temporary directories. Errors during creation are handled. ```flix use Fs.FileWrite def main(): Unit \ { FileWrite, IO } = match FileWrite.mkDirs("a/b/c") { case Ok(_) => println("Created a/b/c.") case Err(err) => println("Error: ${err}") }; match FileWrite.mkTempDir("flix-") { case Ok(path) => println("Temp dir: ${path}") case Err(err) => println("Error: ${err}") } ``` -------------------------------- ### Select with a Default Case Source: https://github.com/flix/book/blob/master/src/concurrency.md Implement a `select` with a default case to avoid blocking indefinitely when no message is immediately available. This example returns 'default' if no messages are received. ```flix def main(): String \ {Chan, NonDet} = region rc { let (_, rx1) = Channel.buffered(1); let (_, rx2) = Channel.buffered(1); select { case _ <- recv(rx1) => "one" case _ <- recv(rx2) => "two" case _ => "default" } ``` -------------------------------- ### First-Class Datalog Constraints in Flix Source: https://github.com/flix/book/blob/master/src/introduction.md Shows how to integrate Datalog constraints directly into Flix code. This example defines a Datalog program to find reachable nodes in a graph represented by a list of edges. ```flix def reachable(edges: List[(Int32, Int32)], src: Int32, dst: Int32): Bool = let db = inject edges into Edge/2; let pr = #{ Path(x, y) :- Edge(x, y). Path(x, z) :- Path(x, y), Edge(y, z). Reachable() :- Path(src, dst). }; let result = query db, pr select () from Reachable(); not Vector.isEmpty(result) ``` -------------------------------- ### Retrieving System Information Source: https://github.com/flix/book/blob/master/src/env.md Illustrates how to fetch OS architecture, version, and the number of virtual processors available. ```flix use Sys.Env def main(): Unit \ { Env, IO } = let name = Env.getOsName(); let arch = Env.getOsArch(); let version = Env.getOsVersion(); let cpus = Env.getVirtualProcessors(); println("OS: ${name}"); println("Arch: ${arch}"); println("Ver: ${version}"); println("CPUs: ${cpus}") ``` -------------------------------- ### Example Rule with Functional Predicate Source: https://github.com/flix/book/blob/master/src/functional-predicates.md An example of a rule that uses a functional predicate to relate variables without exhaustive enumeration. ```flix R(p) :- P(x), Q(y), PrimeInRange(x, y, p). ``` -------------------------------- ### Attempting to Implement a Sealed Trait from Another Module Source: https://github.com/flix/book/blob/master/src/traits.md Shows an example of trying to implement a sealed trait 'Zoo.Animal' from an external module 'Lake', which results in a resolution error. ```flix mod Lake { pub enum Swan instance Zoo.Animal[Swan] { pub def isMammal(_: Swan): Bool = false } } ``` -------------------------------- ### Initialize and Run a Flix Project via CLI Source: https://github.com/flix/book/blob/master/src/getting-started.md Use these commands to create a new Flix project and then compile and run it from the command line. ```shell java -jar flix.jar init ``` ```shell java -jar flix.jar run ``` -------------------------------- ### Send GET Request with Http Source: https://github.com/flix/book/blob/master/src/http-and-https.md Use Http.get to send a simple GET request. It returns a Result, requiring pattern matching for Ok and Err cases. The Http effect supports both http:// and https:// URLs. ```flix use Net.Http use Net.HttpResponse def main(): Unit \ { Http, IO } = match Http.get("http://example.com/") { case Ok(resp) => println(HttpResponse.body(resp)) case Err(err) => println(err) } ``` -------------------------------- ### Accessing Directories and OS Info Source: https://github.com/flix/book/blob/master/src/env.md Demonstrates how to retrieve the user's home directory, current working directory, and operating system name using the Env effect. ```flix use Sys.Env def main(): Unit \ { Env, IO } = let home = Env.getUserHomeDirectory(); println("Home: ${home}"); let cwd = Env.getCurrentWorkingDirectory(); println("CWD: ${cwd}"); let os = Env.getOsName(); println("OS: ${os}") ``` -------------------------------- ### Outdated Flix Annotation Casing Source: https://github.com/flix/book/blob/master/src/for-llms.md This is an example of outdated annotation casing, which is no longer valid. ```flix @test // Wrong -- Outdated def testAdd01(): Bool = 1 + 2 == 3 // Wrong -- Outdated ``` -------------------------------- ### Guessing Game - Wrong Way (Mixed Style) Source: https://github.com/flix/book/blob/master/src/effect-oriented-programming.md This example demonstrates a mixed style of programming where all functions, including those performing IO, are given the IO effect. This leads to effectful code being scattered throughout the program, making it hard to manage. ```flix import java.lang.System import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.{Random => JRandom} def getSecretNumber(): Int32 \ {NonDet, IO} = let rnd = new JRandom(); rnd.nextInt() def readGuess(): Result[String, String] \ IO = let reader = new BufferedReader(new InputStreamReader(System.in)); let line = reader.readLine(); if (Object.isNull(line)) Result.Err("no input") else Result.Ok(line) def readAndParseGuess(): Result[String, Int32] \ IO = forM(g <- readGuess(); n <- Int32.parse(10, g) ) yield n def gameLoop(secret: Int32): Unit \ IO = { println("Enter a guess:"); match readAndParseGuess() { case Result.Ok(g) => if (secret == g) { println("Correct!") } else { println("Incorrect!"); gameLoop(secret) } case Result.Err(_) => println("Not a number? Goodbye."); println("The secret was: ${secret}") } } def main(): Unit \ {NonDet, IO} = let secret = getSecretNumber(); gameLoop(secret) ``` -------------------------------- ### Basic FileSystem Operations: Write and Read Source: https://github.com/flix/book/blob/master/src/filesystem.md Demonstrates the basic usage of writing to a file and then reading its content using the FileSystem effect. Handles potential errors from both operations. ```flix use Fs.FileSystem def main(): Unit \ { FileSystem, IO } = match FileSystem.write(str = "Hello!", "greeting.txt") { case Err(err) => println("Write error: ${err}") case Ok(_) => match FileSystem.read("greeting.txt") { case Ok(content) => println("Read: ${content}") case Err(err) => println("Read error: ${err}") } } ``` -------------------------------- ### Configure Flix LSP Client Source: https://github.com/flix/book/blob/master/src/getting-started.md Set up Neovim's native LSP client for Flix. This includes specifying the command to run the LSP server (either project-local or global) and defining filetypes and root markers. ```lua -- check if "flix" has already been setup if not vim.lsp.config["flix"] then -- create flix LSP configuration for native LSP vim.lsp.config('flix', { -- choose just one `cmd` definition -- for a project local `flix.jar` ie flix.jar is installed in the root of your project cmd = { "java", "-jar", "flix.jar", "lsp" }, -- for a global flix installation ie with "homebrew" or "nix" cmd = {"flix", "lsp"}, filetypes = { "flix" }, root_markers = { "flix.toml" }, -- where to set the root directory cmd_cwd = vim.fs.root(0, { 'flix.toml' }), root_dir = vim.fs.root(0, { 'flix.toml' }) }) end ``` -------------------------------- ### Example Flix Dependencies Source: https://github.com/flix/book/blob/master/src/outdated.md Define package dependencies in the `flix.toml` file. These are the packages that the `outdated` command will check. ```toml [dependencies] "github:flix/museum" = "1.0.0" "github:flix/museum-giftshop" = "1.0.0" ``` -------------------------------- ### Copy, Move, and Delete Files Source: https://github.com/flix/book/blob/master/src/filesystem.md Demonstrates how to copy, move (rename), and delete files using the FileWrite effect. Ensure the file exists before attempting operations. ```flix use Fs.FileWrite def main(): Unit \ { FileWrite, IO } = match FileWrite.write(str = "Hello!", "original.txt") { case Err(err) => println("Write error: ${err}") case Ok(_) => // Copy with no options. match FileWrite.copy(src = "original.txt", "copy.txt") { case Ok(_) => println("Copied.") case Err(err) => println("Copy error: ${err}") }; // Move (rename) with no options. match FileWrite.move(src = "copy.txt", "renamed.txt") { case Ok(_) => println("Moved.") case Err(err) => println("Move error: ${err}") }; // Delete. match FileWrite.delete("renamed.txt") { case Ok(_) => println("Deleted.") case Err(err) => println("Delete error: ${err}") } } ``` -------------------------------- ### Instantiate Java File Object Source: https://github.com/flix/book/blob/master/src/creating-objects.md Demonstrates creating a File object using its constructor. Java classes must be imported. ```flix import java.io.File def main(): Unit \ IO = let f = new File("foo.txt"); println("Hello World!") ``` -------------------------------- ### Unsafe Unchecked Type Cast Triggering Exception Source: https://github.com/flix/book/blob/master/src/unchecked-casts.md An example of an illegal type cast that will cause a ClassCastException at runtime. ```flix unchecked_cast((123, 456) as Integer) ``` -------------------------------- ### Call Higher-Order Function with Lambda Source: https://github.com/flix/book/blob/master/src/functions.md Pass a lambda expression to a higher-order function. This example increments `42` twice. ```flix twice(x -> x + 1, 42) ``` -------------------------------- ### Execute Process with Custom Working Directory and Environment Source: https://github.com/flix/book/blob/master/src/process.md Utilize `Process.execWithCwd` to specify a working directory for a new process. Use `Process.execWithEnv` to pass custom environment variables. ```flix use Sys.Process def main(): Unit \ { Process, IO } = match Process.execWithCwd("java", "-version" :: Nil, Some("/tmp")) { case Result.Ok(_) => println("execWithCwd succeeded.") case Result.Err(err) => println("execWithCwd failed: ${err}") }; match Process.execWithEnv("java", "-version" :: Nil, Map#{"MY_VAR" => "hello"}) { case Result.Ok(_) => println("execWithEnv succeeded.") case Result.Err(err) => println("execWithEnv failed: ${err}") } ``` -------------------------------- ### Basic Console Input/Output Source: https://github.com/flix/book/blob/master/src/console.md Demonstrates a simple interaction: printing a prompt, reading user input, and then printing a greeting. ```flix use Sys.Console def main(): Unit \ Console = Console.print("What is your name? "); let name = Console.readln(); Console.println("Hello ${name}!") ``` -------------------------------- ### Rejecting Unused Local Variable Source: https://github.com/flix/book/blob/master/src/redundancy.md This example demonstrates a Flix program rejected by the compiler due to an unused local variable 'y'. ```flix def main(): Unit \ IO = let x = 123; let y = 456; println("The sum is ${x + x}") ``` -------------------------------- ### Pure Higher-Order Function Signature Source: https://github.com/flix/book/blob/master/src/effect-polymorphism.md Example of a higher-order function `exists` that enforces its predicate argument `f` to be pure (have no effects). ```flix def exists(f: a -> Bool \ { }, s: Set[a]): Bool = ... ``` -------------------------------- ### Writing and Reading Bytes from a File Source: https://github.com/flix/book/blob/master/src/filesystem.md Shows how to write binary data to a file using `writeBytes` and read it back with `readBytes`. This is suitable for non-textual data. Requires `FileRead`, `FileWrite`, and `IO` effects. ```flix use Fs.FileRead use Fs.FileWrite def main(): Unit \ { FileRead, FileWrite, IO } = let data = Vector#{72i8, 101i8, 108i8, 108i8, 111i8}; match FileWrite.writeBytes(data, "binary.dat") { case Err(err) => println("Write error: ${err}") case Ok(_) -> match FileRead.readBytes("binary.dat") { case Ok(bytes) -> println("Read ${Vector.length(bytes)} bytes."); println("As string: ${String.fromBytes(bytes)}") case Err(err) => println("Read error: ${err}") } } ``` -------------------------------- ### Getting Array Length Source: https://github.com/flix/book/blob/master/src/arrays.md Use `Array.length` to compute the number of elements in an array. This is a common operation for understanding array bounds. ```flix region rc { let fruits = Array#{"Apple", "Pear", "Mango"} @ rc; println(Array.length(fruits)) } ``` -------------------------------- ### Incorrect Nested Run Blocks Source: https://github.com/flix/book/blob/master/src/for-llms.md Avoid nesting `run` blocks. This example shows the incorrect way to handle multiple effects. ```flix use Math.Random use Time.Duration.{seconds} use Time.Sleep def main(): Unit \ { Logger, Random, Sleep, IO } = run { run { println("Sleeping 3 times with ±20% jitter..."); Sleep.sleep(seconds(1)); Sleep.sleep(seconds(2)); Sleep.sleep(seconds(3)); println("Done!") } with Sleep.withJitter(0.2) } with Sleep.withLogging ``` -------------------------------- ### Create and Populate MutList Source: https://github.com/flix/book/blob/master/src/mutable-collections.md Demonstrates creating an empty mutable list and adding elements to it using push. The list automatically expands as needed. ```flix def main(): Unit \ IO = region rc { let fruits = MutList.empty(rc); MutList.push("Apple", fruits); MutList.push("Pear", fruits); MutList.push("Mango", fruits); MutList.forEach(println, fruits) } ``` -------------------------------- ### Basic String Interpolation with Variables Source: https://github.com/flix/book/blob/master/src/string-interpolation.md Demonstrates basic string interpolation using string variables. Ensure variables are declared before use. ```flix let fstName = "Lucky"; let lstName = "Luke"; "Hello Mr. ${lstName}. Do you feel ${fstName}, punk?" ``` -------------------------------- ### Cannot Declare Polymorphic Effects Source: https://github.com/flix/book/blob/master/src/effects-and-handlers.md Flix's type and effect system does not support polymorphic effects. This example shows the syntax that is not allowed. ```flix eff Throw[a] { def throw(x: a): Void } ``` -------------------------------- ### Composing File System Middleware Source: https://github.com/flix/book/blob/master/src/filesystem.md This snippet demonstrates stacking multiple file system middleware handlers using 'with' clauses. The order of composition is crucial, with the last 'with' clause being the outermost handler. ```flix use Fs.FileSystem def main(): Unit \ { FileSystem, Logger, IO } = run { match FileSystem.write(str = "Hello, Flix!", "data/greeting.txt") { case Err(err) => println("Write error: ${err}") case Ok(_) => match FileSystem.read("data/greeting.txt") { case Ok(content) => println("Read: ${content}") case Err(err) => println("Read error: ${err}") } } } with FileSystem.withBaseDir("/tmp/flix-example") with FileSystem.withMkParentDirs with FileSystem.withConflictCheck with FileSystem.withBackup(".bak") with FileSystem.withAtomicWrite with FileSystem.withLogging ``` -------------------------------- ### Pipeline of Fixpoint Computations Source: https://github.com/flix/book/blob/master/src/fixpoints.md Demonstrates constructing a pipeline where the result of one fixpoint computation (`m`) is used as input for subsequent queries and computations. This involves defining initial facts, recursive rules, and then projecting and querying the results. ```flix def main(): Unit \ IO = let f1 = #{ ColorEdge(1, "blue", 2). ColorEdge(2, "blue", 3). ColorEdge(3, "red", 4). }; let r1 = #{ ColorPath(x, c, y) :- ColorEdge(x, c, y). ColorPath(x, c, z) :- ColorPath(x, c, y), ColorEdge(y, c, z). }; let r2 = #{ ColorlessPath(x, y) :- ColorPath(x, _, y). }; let m = solve f1, r1 project ColorPath; query m, r2 select (x, y) from ColorlessPath(x, y) |> println ``` -------------------------------- ### Clock Effect Definition Source: https://github.com/flix/book/blob/master/src/clock.md Defines the Clock effect with a single operation `currentTime` to get the time since the epoch in a specified unit. ```flix pub eff Clock { /// Returns a measure of time since the epoch in the given time unit `u`. def currentTime(u: TimeUnit): Int64 } ``` -------------------------------- ### Modifying Struct Fields Source: https://github.com/flix/book/blob/master/src/structs.md Read and write struct fields using the '->' operator. This example increments the age and conditionally modifies height. ```flix mod Person { pub def birthday(p: Person[r]): Unit \ r = p->age = p->age + 1; if(p->age < 18) { p->height = p->height + 10 } else { () } } ``` -------------------------------- ### Non-Tail Recursive Factorial Source: https://github.com/flix/book/blob/master/src/tail-recursion.md An example of a factorial function where the recursive call is not in tail position, leading to potential stack overflows for large inputs. ```flix def factorial(n: Int32): Int32 = match n { case 0 => 1 case _ => n * factorial(n - 1) } ``` -------------------------------- ### Running Leaf Filesystem Effects Source: https://github.com/flix/book/blob/master/src/filesystem.md Demonstrates how to run leaf effects like `FileExists` and `ReadFile` into their parent effects (`FileTest` and `FileRead` respectively) using `runWith` handlers. This allows for more granular control and composition of filesystem operations. ```flix use Fs.FileExists use Fs.FileRead use Fs.FileTest use Fs.ReadFile def main(): Unit \ { FileRead, FileTest, IO } = run { safeRead("example.txt") } with FileExists.runWithFileTest with ReadFile.runWithFileRead def safeRead(file: String): Unit \ { FileExists, ReadFile, IO } = match FileExists.exists(file) { case Err(err) => println("Error: ${err}") case Ok(false) => println("File does not exist") case Ok(true) => match ReadFile.read(file) { case Ok(content) => println(content) case Err(err) => println("Read error: ${err}") } } ``` -------------------------------- ### Exiting a Flix Program Source: https://github.com/flix/book/blob/master/src/main.md This example demonstrates how to terminate a Flix program with a specific exit code (0 in this case) using the Exit effect. ```flix use Sys.Exit def main(): Unit \ Exit = Exit.exit(0) ``` -------------------------------- ### Example Output of Lazy Stream Operations Source: https://github.com/flix/book/blob/master/src/laziness.md The result of applying `map` and `take` to an infinite stream, showing the first 10 computed integers. ```flix 52 :: 53 :: 54 :: 55 :: 56 :: 57 :: 58 :: 59 :: 60 :: 61 :: Nil ``` -------------------------------- ### Multiple Constructor Overloads with Different Types Source: https://github.com/flix/book/blob/master/src/creating-objects.md Illustrates using constructors with different argument types, including a URI object, for the File class. ```flix import java.io.File import java.net.URI def main(): Unit \ IO = let f1 = new File("foo.txt"); let f2 = new File("bar", "foo.txt"); let f3 = new File(new URI("file://foo.txt")); println("Hello World!") ``` -------------------------------- ### Unhandled Effects in Spawn Expression Source: https://github.com/flix/book/blob/master/src/effects-and-handlers.md Flix prohibits unhandled effects in spawn expressions. This example demonstrates an illegal spawn of an effectful computation. ```flix eff Ask { def ask(): String } def main(): Unit \ IO = region rc { spawn Ask.ask() @ rc } ``` -------------------------------- ### Function vs. Match Lambda with Multiple Arguments Source: https://github.com/flix/book/blob/master/src/pattern-matching.md Illustrates the difference between a standard function definition taking multiple arguments and a match lambda expecting a single tuple argument. ```flix let f = (x, y, z) -> x + y + z + 42i32 let g = match (x, y, z) -> x + y + z + 42i32 ``` -------------------------------- ### Define a Higher-Order Function Source: https://github.com/flix/book/blob/master/src/functions.md A higher-order function accepts another function as a parameter. This example applies a function `f` twice to an integer `x`. ```flix def twice(f: Int32 -> Int32, x: Int32): Int32 = f(f(x)) ``` -------------------------------- ### Composing Jitter and Logging Middleware Source: https://github.com/flix/book/blob/master/src/sleep.md Demonstrates composing `withJitter` and `withLogging` to add random jitter and log sleep durations. ```flix use Math.Random use Time.Duration.{seconds} use Time.Sleep /// Composes `withJitter` and `withLogging` to add ±20% random jitter /// to sleep durations and log each sleep via the `Logger` effect. def main(): Unit \ { Logger, Random, Sleep, IO } = run { println("Sleeping 3 times with ±20% jitter..."); Sleep.sleep(seconds(1)); Sleep.sleep(seconds(2)); Sleep.sleep(seconds(3)); println("Done!") } with Sleep.withJitter(0.2) with Sleep.withLogging ``` -------------------------------- ### FileSystem with Base Directory Middleware Source: https://github.com/flix/book/blob/master/src/filesystem.md Applies the withBaseDir middleware to resolve relative paths against a specified base directory. Absolute paths are unaffected. Demonstrates writing and reading within the base directory. ```flix use Fs.FileSystem def main(): Unit \ { FileSystem, IO } = match FileSystem.mkDirs("/tmp/flix-basedir") { case Err(err) => println("Setup error: ${err}") case Ok(_) => run { match FileSystem.write(str = "Hello", "greeting.txt") { case Err(err) => println("Write error: ${err}") case Ok(_) => match FileSystem.read("greeting.txt") { case Ok(content) => println("Read: ${content}") case Err(err) => println("Read error: ${err}") } } } with FileSystem.withBaseDir("/tmp/flix-basedir") ``` -------------------------------- ### Writing and Reading Lines from a File Source: https://github.com/flix/book/blob/master/src/filesystem.md Demonstrates writing multiple lines to a file using `writeLines` and then reading them back with `readLines`. Requires `FileRead`, `FileWrite`, and `IO` effects. ```flix use Fs.FileRead use Fs.FileWrite def main(): Unit \ { FileRead, FileWrite, IO } = match FileWrite.writeLines(lines = List#{"Line 1", "Line 2", "Line 3"}, "data.txt") { case Err(err) => println("Write error: ${err}") case Ok(_) -> match FileRead.readLines("data.txt") { case Ok(lines) -> foreach (line <- lines) { println(line) } case Err(err) => println("Read error: ${err}") } } ``` -------------------------------- ### Reading Environment Variables Source: https://github.com/flix/book/blob/master/src/env.md Shows how to read a specific environment variable like 'PATH' or retrieve all environment variables as a map. ```flix use Sys.Env def main(): Unit \ { Env, IO } = let path = Env.getVar("PATH"); println("PATH: ${path}"); let all = Env.getEnv(); println("Total env vars: ${Map.size(all)}) ``` -------------------------------- ### Accessing Vector Element by Index Source: https://github.com/flix/book/blob/master/src/chains-and-vectors.md Example of retrieving an element from a Vector at a specific index using Vector.get. Be cautious of out-of-bounds access, which will panic. ```flix let v = Vector#{1, 2, 3}; println(Vector.get(2, v)) ``` -------------------------------- ### Slicing Arrays Source: https://github.com/flix/book/blob/master/src/arrays.md The `Array.slice` function creates a new shallow copy of a sub-range of an array. Specify the start and end indices to define the slice. ```flix region rc { let fruits = Array#{"Apple", "Pear", "Mango"} @ rc; let result = Array.slice(rc, start = 1, end = 2, fruits); println(Array.toString(result)) } ``` -------------------------------- ### Creating a Struct Instance Source: https://github.com/flix/book/blob/master/src/structs.md Instantiate a new struct with initial field values. All fields must be initialized explicitly. ```flix mod Person { pub def mkLuckyLuke(rc: Region[r]): Person[r] \ r = new Person @ rc { name = "Lucky Luke", age = 30, height = 185 } } new Person @ rc { name = "Lucky Luke", age = 30, height = 185 } ``` -------------------------------- ### Using Effects with Default Handlers in Tests Source: https://github.com/flix/book/blob/master/src/default-handlers.md This example demonstrates using effects with default handlers within a test function, leveraging the `@Test` annotation. ```flix @Test def myTest01(): Unit \ {Assert, Logger} = Logger.info("Running test!"); Assert.assertEq(expected = 42, 42) ``` -------------------------------- ### Using Assert with Default Handler Source: https://github.com/flix/book/blob/master/src/assert.md Demonstrates basic assertion usage with the default handler, which throws an AssertionError on failure. No explicit handler is needed for `main`. ```flix use Assert.{assertTrue, assertFalse, assertEq, assertNeq} def main(): Unit \ { Assert, IO } = assertTrue(1 + 1 == 2); assertFalse(1 > 2); assertEq(expected = 4, 2 + 2); assertNeq(unexpected = 0, 1 + 1); println("All assertions passed!") ``` -------------------------------- ### Call `getName` on a Java File object Source: https://github.com/flix/book/blob/master/src/calling-methods.md Demonstrates importing a Java class, instantiating an object, and calling a method on it. ```flix import java.io.File def main(): Unit \ IO = let f = new File("foo.txt"); println(f.getName()) ``` -------------------------------- ### Use Derived ToString with String Interpolation Source: https://github.com/flix/book/blob/master/src/automatic-derivation.md Example of using the derived `ToString` implementation with Flix's string interpolation to print enum values. ```flix def main(): Unit \ IO = let c = Circle(123); let s = Square(123); let r = Rectangle(123, 456); println("A ${c}, ${s}, and ${r} walk into a bar.") ``` -------------------------------- ### Call Nested Module Functions Directly Source: https://github.com/flix/book/blob/master/src/declaring-modules.md Functions within nested modules can be called using their fully qualified path, starting from the root module. ```flix def main(): Unit \ IO = Museum.Entrance.buyTicket(); Museum.Restaurant.buyMeal(); Museum.Giftshop.buyGift() ``` -------------------------------- ### Non-Tail Recursive Length (Rejected by @Tailrec) Source: https://github.com/flix/book/blob/master/src/tail-recursion.md An example of a length function that is not tail-recursive. The @Tailrec annotation will cause a compile-time error because the recursive call is not in tail position. ```flix @Tailrec def length(l: List[Int32]): Int32 = match l { case Nil => 0 case _ :: xs => length(xs) + 1 } ``` -------------------------------- ### Sleep with Max Duration and Logging Middleware Source: https://github.com/flix/book/blob/master/src/sleep.md Illustrates using `withMaxSleep` to cap sleep durations and `withLogging` to log them. ```flix use Time.Duration.{milliseconds, seconds} use Time.Sleep def main(): Unit \ { Logger, Sleep, IO } = run { println("Sleeping for 2 seconds (capped to 500ms)..."); Sleep.sleep(seconds(2)); println("Done!") } with Sleep.withMaxSleep(milliseconds(500)) with Sleep.withLogging ``` -------------------------------- ### Create and Print an Array Literal Source: https://github.com/flix/book/blob/master/src/arrays.md Demonstrates how to create an array of strings using an array literal and print its contents. Requires defining a region. ```flix region rc { let fruits = Array#{"Apple", "Pear", "Mango"} @ rc; println(Array.toString(fruits)) } ``` -------------------------------- ### Allocate Array with Integer Range Source: https://github.com/flix/book/blob/master/src/arrays.md Use `Array.range` to create an array containing integers from a start to an end value (exclusive). The region must be passed as an argument. ```flix region rc { let arr = Array.range(rc, 0, 100); println(Array.toString(arr)) } ``` -------------------------------- ### Infix Function Application Source: https://github.com/flix/book/blob/master/src/functions.md Demonstrates how to use infix function application by enclosing a function name in backticks, equivalent to a normal function call. ```flix 123 `sum` 456 ```