### Example Java Version Output Source: https://doc.flix.dev/print This is an example output of the 'java -version' command, indicating that OpenJDK version 21 is installed. This meets the minimum requirement for Flix. ```text __ openjdk version "21" 2023-09-19 LTS OpenJDK Runtime Environment Temurin-21+35 (build 21+35-LTS) OpenJDK 64-Bit Server VM Temurin-21+35 (build 21+35-LTS, mixed mode, sharing) ``` -------------------------------- ### Install Flix using Nix Package Manager (Shell) Source: https://doc.flix.dev/getting-started This command installs the Flix package for the currently running shell environment using the Nix package manager. This is a temporary installation that will be available only within the current shell session. ```bash $ nix-shell -p flix ``` -------------------------------- ### Install Flix using Nix Package Manager (Global) Source: https://doc.flix.dev/getting-started This command installs the Flix package globally on your system using the Nix package manager. This makes the `flix` command available in any shell session without needing to activate a specific environment. ```bash $ nix-env -i flix ``` -------------------------------- ### Flix Chain Construction Example Source: https://doc.flix.dev/chains-and-vectors Demonstrates how to construct a Chain in Flix using `Chain.cons` and `Chain.empty`. This example shows the creation of a simple chain with a single element. ```flix __ let c = Chain.cons(1, Chain.empty()); println(c) ``` -------------------------------- ### Check Java Version Source: https://doc.flix.dev/print This command-line snippet shows how to check the installed Java version. It's a prerequisite for installing and using Flix, which requires Java 21 or later. ```bash $ java -version ``` -------------------------------- ### String Interpolation Example Source: https://doc.flix.dev/print Illustrates Flix's string interpolation syntax. The example shows how `${variable}` placeholders within a string are syntactic sugar for concatenating string literals with calls to `ToString.toString`. ```flix "Good morning " + ToString.toString(name) + ", it is " + ToString.toString(hour) + " o'clock." ``` -------------------------------- ### Higher-Order Function Example in Flix Source: https://doc.flix.dev/print Demonstrates higher-order functions in Flix, where functions can accept other functions as arguments. The `twice` function takes a function `f` and an integer `x`, applying `f` twice to `x`. Examples show passing lambda expressions and top-level functions as arguments. ```flix def twice(f: Int32 -> Int32, x: Int32): Int32 = f(f(x)) twice(x -> x + 1, 42) def inc(x: Int32): Int32 = x + 1 twice(inc, 42) ``` -------------------------------- ### Flix Unit Tests with Assertions Source: https://doc.flix.dev/test-framework Demonstrates writing unit tests in Flix using the `@Test` annotation and various assertion functions from the `Assert` module. It includes examples for testing arithmetic operations, boolean conditions, and result types. ```flix use Assert.{assertEq, assertTrue, assertFalse, assertOk, assertErr} def add(x: Int32, y: Int32): Int32 = x + y def isEven(x: Int32): Bool = Int32.modulo(x, 2) == 0 def safeDivide(x: Int32, y: Int32): Result[String, Int32] = if (y == 0) Err("Division by zero") else Ok(x / y) @Test def testAdd01(): Unit \ Assert = assertEq(expected = 5, add(2, 3)) @Test def testIsEven01(): Unit \ Assert = assertTrue(isEven(4)) @Test def testIsEven02(): Unit \ Assert = assertFalse(isEven(3)) @Test def testSafeDivide01(): Unit \ Assert = assertOk(safeDivide(10, 2)) @Test def testSafeDivide02(): Unit \ Assert = assertErr(safeDivide(10, 0)) ``` -------------------------------- ### Using Derived Eq and Order Instances Source: https://doc.flix.dev/print Provides an example of using the automatically derived `Eq` and `Order` instances for the `Shape` enum. It shows comparisons for equality, inequality, and ordering, demonstrating the structural comparison logic. ```flix def main(): Unit \ IO = println(Circle(123) == Circle(123)); // prints `true`. println(Circle(123) != Square(123)); // prints `true`. println(Circle(123) <= Circle(123)); // prints `true`. println(Circle(456) <= Square(123)) // prints `true`. ``` -------------------------------- ### Structured Concurrency with Channels and Processes in Flix Source: https://doc.flix.dev/index Illustrates structured concurrency in Flix using channels and processes. This example includes functions to send all elements of a list, receive a specified number of elements, and coordinate these operations. ```flix /// A function that sends every element of a list def sendAll(l: List[Int32], tx: Sender[Int32]): Unit \ Chan = match l { case Nil => () case x :: xs => Channel.send(x, tx); sendAll(xs, tx) } /// A function that receives n elements /// and collects them into a list. def recvN(n: Int32, rx: Receiver[Int32]): List[Int32] \ {Chan, NonDet} = match n { case 0 => Nil case _ => Channel.recv(rx) :: recvN(n - 1, rx) } /// A function that calls receive and sends the result on d. def wait(rx: Receiver[Int32], n: Int32, tx: Sender[List[Int32]]): Unit \ {Chan, NonDet} = Channel.send(recvN(n, rx), tx) ``` -------------------------------- ### Execute External Commands with ProcessWithResult in Flix Source: https://doc.flix.dev/print Demonstrates the use of the ProcessWithResult effect to execute external commands. The example shows how to run the 'ls' command and handle potential errors during execution. ```flix __ eff ProcessWithResult { /// Executes the command `cmd` with the arguments `args`, by the path `cwd` /// and with the environment `env`. def execWithCwdAndEnv(cmd: String, args: List[String], cwd: Option[String], env: Map[String, String]): Result[IoError, ProcessHandle] // ... additional operations (exitValue, isAlive, pid, stop, waitFor, waitForTimeout) ... } mod Process { /// Executes the command `cmd` with the arguments `args`. pub def exec(cmd: String, args: List[String]) : Result[IoError, ProcessHandle] ProcessWithResult /// Executes the command `cmd` with the arguments `args`, by the path `cwd`. def execWithCwd(cmd: String, args: List[String], cwd: Option[String]) : Result[IoError, ProcessHandle] ProcessWithResult /// Executes the command `cmd` with the arguments `args` and with /// the environment `env`. def execWithEnv(cmd: String, args: List[String], env: Map[String, String]) : Result[IoError, ProcessHandle] ProcessWithResult } __ def main(): Unit IO = run { match ProcessWithResult.exec("ls", Nil) { case Result.Ok(_) => () case Result.Err(err) => println("Unable to execute process: ${err}") } } with ProcessWithResult.runWithIO ``` -------------------------------- ### Using Console for User Input and Output in Flix Source: https://doc.flix.dev/print Shows an example of using the `Console` effect in Flix to interact with the user. It prompts the user for their name, reads the input, and then prints a greeting. This operation requires the `Console.runWithIO` context. ```flix __ def main(): Unit \ IO = run { Console.println("Please enter your name: "); let name = Console.readln(); Console.println("Hello ${name}") } with Console.runWithIO ``` -------------------------------- ### First-Class Datalog Constraints in Flix Source: https://doc.flix.dev/index Shows how to integrate first-class Datalog constraints within Flix programs. This example defines a Datalog program to determine reachability between nodes in a graph represented by 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) ``` -------------------------------- ### Defining Custom Effects and Handlers in Flix Source: https://doc.flix.dev/index Demonstrates how to define and use custom effects and handlers in Flix. This example defines `MyPrint` and `MyTime` effects and uses them to create a greeting function with custom handling. ```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) } ``` -------------------------------- ### Flix Default Handlers Translation to IO Source: https://doc.flix.dev/print Shows the equivalent IO-based execution of the previous example that uses default handlers for Clock, Env, and Logger effects. The Flix compiler automatically inserts `runWithIO` calls for each effect. ```flix def main(): Unit \ IO = run { let ts = Clock.currentTime(TimeUnit.Milliseconds); let os = Env.getOsName(); Logger.info("UNIX Timestamp: ${ts}"); Logger.info("Operating System: ${os}") } with Clock.runWithIO with Env.runWithIO with Logger.runWithIO ``` -------------------------------- ### Flix Type Ascription for List of Strings Source: https://doc.flix.dev/print Shows how to use type ascriptions in Flix to explicitly declare the type of an expression or let-binding. This example demonstrates a type ascription on a list of strings, ensuring clarity and aiding the compiler. ```flix (("Hello" :: "World" :: Nil) : List[String]) ``` ```flix let l: List[String] = "Hello" :: "World" :: Nil ``` -------------------------------- ### Create Array Literal Source: https://doc.flix.dev/print Demonstrates the creation of an array using literal syntax. An array literal consists of element expressions and a region expression. The example shows an array of strings initialized with 'Apple', 'Pear', and 'Mango'. ```flix region rc { let fruits = Array#{"Apple", "Pear", "Mango"} @ rc; println(Array.toString(fruits)) } ``` -------------------------------- ### Example: Using HttpWithResult in Flix Source: https://doc.flix.dev/library-effects Demonstrates how to use the HttpWithResult effect to perform an HTTP GET request and print the response body or an error message. ```flix def main(): Unit \ IO = run { match HttpWithResult.get("http://example.com/", Map.empty()) { case Result.Ok(response) => let body = Http.Response.body(response); println(body) case Result.Err(e) => println(e) } } with HttpWithResult.runWithIO ``` -------------------------------- ### Spawn and Wait Process with Channel Communication (OCaml) Source: https://doc.flix.dev/introduction This snippet demonstrates spawning a process to send data and another to wait for it, utilizing buffered channels for inter-process communication. It shows how to initialize channels, spawn asynchronous tasks, and receive the final result. ```ocaml /// Spawn a process for send and wait, and print the result. def main(): Unit \ {Chan, NonDet, IO} = region rc { let l = 1 :: 2 :: 3 :: Nil; let (tx1, rx1) = Channel.buffered(100); let (tx2, rx2) = Channel.buffered(100); spawn sendAll(l, tx1) @ rc; spawn wait(rx1, List.length(l), tx2) @ rc; println(Channel.recv(rx2)) } ``` -------------------------------- ### Define and Use HttpWithResult Effect in Flix Source: https://doc.flix.dev/print Defines the HttpWithResult effect for performing HTTP requests and provides examples of its usage, specifically for sending a GET request. It shows how to handle successful responses and errors. ```flix __ eff HttpWithResult { def request(method: String, url: String, headers: Map[String, List[String]], body: Option[String]) : Result[IoError, Http.Response] } mod HttpWithResult { /// Send a `GET` request to the given `url` with the given `headers` /// and wait for the response. def get(url: String, headers: Map[String, List[String]]) : Result[IoError, Http.Response] HttpWithResult /// Send a `POST` request to the given `url` with the given `headers` /// and `body` and wait for the response. def post(url: String, headers: Map[String, List[String]], body: String) : Result[IoError, Http.Response] HttpWithResult /// Send a `PUT` request to the given `url` with the given `headers` /// and `body` and wait for the response. def put(url: String, headers: Map[String, List[String]], body: String) : Result[IoError, Http.Response] HttpWithResult // ... additional functions (head, delete, options, trace, patch) ... } __ def main(): Unit IO = run { match HttpWithResult.get("http://example.com/", Map.empty()) { case Result.Ok(response) => let body = Http.Response.body(response); println(body) case Result.Err(e) => println(e) } } with HttpWithResult.runWithIO ``` -------------------------------- ### Spawn and Wait Process with Channel Communication (OCaml) Source: https://doc.flix.dev/index This snippet demonstrates spawning a 'sendAll' process and a 'wait' process, communicating through buffered channels. It utilizes OCaml's concurrency features to manage these processes and print the final result received from the 'wait' process. ```ocaml /// Spawn a process for send and wait, and print the result. def main(): Unit {Chan, NonDet, IO} = region rc { let l = 1 :: 2 :: 3 :: Nil; let (tx1, rx1) = Channel.buffered(100); let (tx2, rx2) = Channel.buffered(100); spawn sendAll(l, tx1) @ rc; spawn wait(rx1, List.length(l), tx2) @ rc; println(Channel.recv(rx2)) } ``` -------------------------------- ### Create Array with Integer Range Source: https://doc.flix.dev/print Illustrates the use of `Array.range` to create an array containing a sequence of integers. The function takes a region, a start value, and an end value (exclusive). The example generates an array of integers from 0 to 99. ```flix region rc { let arr = Array.range(rc, 0, 100); println(Array.toString(arr)) } ``` -------------------------------- ### Create and Print a Chain in Flix Source: https://doc.flix.dev/print Demonstrates the creation of a simple Chain in Flix using `Chain.cons` and `Chain.empty`, and printing its value. This illustrates basic Chain construction. ```flix let c = Chain.cons(1, Chain.empty()); println(c) ``` -------------------------------- ### Implementing a Counter with Reference Cells Source: https://doc.flix.dev/print Shows how to implement a reusable counter using Flix reference cells. It defines a `Counter` data type, functions to create (`newCounter`), get the count (`getCount`), and increment (`increment`) the counter. This example highlights the use of regions and effects for mutable state. ```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 } ``` -------------------------------- ### Instantiate Java File Object with Different Constructors (Flix) Source: https://doc.flix.dev/print Shows how to instantiate a Java `File` object using different constructors based on the number and types of arguments provided. Flix resolves the correct constructor automatically. ```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!") ``` -------------------------------- ### Implement Resumable Effects with Flix Source: https://doc.flix.dev/effects-and-handlers Shows how to implement resumable effects in Flix using the `HourOfDay` effect. This example demonstrates capturing the current continuation and resuming it within the handler, utilizing Java interoperability to get the current hour. The handler for `HourOfDay` uses a `resume` function to pass the obtained hour back into the computation. ```flix __ import java.time.LocalDateTime eff HourOfDay { def getCurrentHour(): Int32 } def greeting(): String \ {HourOfDay} = let h = HourOfDay.getCurrentHour(); if (h <= 12) "Good morning" else if (h <= 18) "Good afternoon" else "Good evening" def main(): Unit \ IO = run { println(greeting()) } with handler HourOfDay { def getCurrentHour(_, resume) = let dt = LocalDateTime.now(); resume(dt.getHour()) } ``` -------------------------------- ### Using 'use' within Flix Modules and Functions Source: https://doc.flix.dev/print Illustrates the application of the 'use' construct both at the module level and within function bodies in Flix. Shows how to import types and functions for use in subsequent code, including the use of semicolons for in-expression imports. ```flix mod A { use Chain use Chain.Empty use Chain.Chain use Int32.max pub def maxValue(c: Chain[Int32]): Int32 = match c { case Empty => 0 case One(x) => x case Chain(x, y) => max(maxValue(x), maxValue(y)) } } ``` ```flix mod A { use Chain pub def maxValue(c: Chain[Int32]): Int32 = use Chain.Empty; use Chain.Chain; use Int32.max; match c { case Empty => 0 case One(x) => x case Chain(x, y) => max(maxValue(x), maxValue(y)) } } ``` -------------------------------- ### Handle Multiple Effects (Ask and Say) in Flix Source: https://doc.flix.dev/print Demonstrates handling multiple effects, `Ask` and `Say`, within a single Flix program. The `greeting` function uses both effects to get a name and then print a personalized greeting. The `main` function provides handlers for both `Ask` (resuming with a fixed name) and `Say` (printing to the console), showcasing combined effect management. ```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() } } ``` -------------------------------- ### Flix Vector Map Operation Example Source: https://doc.flix.dev/chains-and-vectors Shows how to use the `Vector.map` operation in Flix to apply a function to each element of a vector. This example increments each element by one. ```flix __ let v = Vector#{1, 2, 3}; Vector.map(x -> x + 1, v) ``` -------------------------------- ### Flix Fixpoint Computation for Pathfinding Source: https://doc.flix.dev/print Demonstrates solving a pathfinding problem using Flix's Datalog integration for fixpoint computation. It defines rules for path existence and queries for a specific path between source and destination nodes. ```flix def isConnected(s: Set[(Int32, Int32)], src: Int32, dst: Int32): Bool = let rules = #{ Path(x, y) :- Edge(x, y). Path(x, z) :- Path(x, y), Edge(y, z). }; let edges = inject s into Edge/2; let paths = query edges, rules select true from Path(src, dst); not (paths |> Vector.isEmpty) def main(): Unit \ IO = let s = Set#{(1, 2), (2, 3), (3, 4), (4, 5)}; let src = 1; let dst = 5; if (isConnected(s, src, dst)) { println("Found a path between ${src} and ${dst}!") } else { println("Did not find a path between ${src} and ${dst}!") } ``` -------------------------------- ### Example: Using Flix Random Effect for a Coin Flip Source: https://doc.flix.dev/library-effects This example demonstrates the use of the Random effect to simulate a coin flip. It calls `Random.randomBool()` and prints 'heads' or 'tails' based on the result. ```flix def main(): Unit \ {NonDet, IO} = run { let flip = Random.randomBool(); if (flip) println("heads") else println("tails") } with Random.runWithIO ``` -------------------------------- ### Instantiate Java File Object with URI Constructor (Flix) Source: https://doc.flix.dev/print Illustrates creating a Java `File` object using a `java.net.URI` constructor. This requires importing both `java.io.File` and `java.net.URI`. ```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!") ``` -------------------------------- ### Flix Monadic forM Example Source: https://doc.flix.dev/applicative-for-yield Illustrates the usage of Flix's monadic 'forM' expression, where the result of one operation is used as input for another. This example shows a sequential computation within the 'Some' context. ```flix forM(x <- Some(123); y <- Some(x)) yield (x, y) ``` -------------------------------- ### Example: Using Flix ProcessWithResult to Execute a Command Source: https://doc.flix.dev/library-effects This example demonstrates how to use the `ProcessWithResult.exec` function to run the 'ls' command. It handles the result of the command execution, printing a success message or an error message if the command fails. ```flix def main(): Unit \ IO = run { match ProcessWithResult.exec("ls", Nil) { case Result.Ok(_) => () case Result.Err(err) => println("Unable to execute process: ${err}") } } with ProcessWithResult.runWithIO ``` -------------------------------- ### Receive Message from Multiple Channels using Select Source: https://doc.flix.dev/print Illustrates using the `select` expression to receive a message from one of multiple channels. This example spawns two processes that send messages on separate buffered channels, and `select` waits for the first message to arrive. It requires the `Chan` effect. ```source 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 ``` -------------------------------- ### Implement Closeable Interface in Flix Source: https://doc.flix.dev/extending-classes-and-interfaces This example shows how to create a Flix object implementing the `java.io.Closeable` interface. The `newClosable` function returns a `Closeable` object with a `close` method that prints 'I am closing!'. Similar to other examples, the `this` argument is explicitly provided. ```flix import java.io.Closeable def newClosable(): Closeable \ IO = new Closeable { def close(_this: Closeable): Unit \ IO = println("I am closing!") } ``` -------------------------------- ### Implementing Java Interfaces in Flix Source: https://doc.flix.dev/print Demonstrates creating Flix objects that implement Java interfaces, similar to Java's anonymous classes. Examples show implementing java.lang.Runnable and java.io.Closeable, highlighting the explicit passing of the 'this' argument. ```flix import java.lang.Runnable def newRunnable(): Runnable IO = new Runnable { def $run(_this: Runnable): Unit IO = println("I am running!") } ``` ```flix import java.io.Closeable def newClosable(): Closeable IO = new Closeable { def close(_this: Closeable): Unit IO = println("I am closing!") } ``` -------------------------------- ### Illegal Non-Exhaustive Let-Binding Source: https://doc.flix.dev/print Provides examples of illegal let-bindings that use non-exhaustive patterns, which the Flix compiler will reject. ```flix let (1, 2, z) = ... let Some(x) = ... ``` -------------------------------- ### Initialize and Populate MutList in Flix Source: https://doc.flix.dev/print Demonstrates the initialization of an empty mutable list ('MutList') within a specified region 'rc' and subsequently pushing elements ('Apple', 'Pear', 'Mango') into it. Finally, it iterates through the list and prints each element. ```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) } ``` -------------------------------- ### Send and Receive Message Over Unbuffered Channel Source: https://doc.flix.dev/print Demonstrates creating an unbuffered channel, spawning a process to send a message, and receiving the message. This function requires the `Chan`, `NonDet`, and `IO` effects. ```source def main(): Int32 \ {Chan, NonDet, IO} = region rc { let (tx, rx) = Channel.unbuffered(); spawn Channel.send(42, tx) @ rc; Channel.recv(rx) } ``` -------------------------------- ### HttpWithResult API Source: https://doc.flix.dev/print The HttpWithResult effect enables making HTTP requests (GET, POST, PUT, etc.) and handling the responses or potential I/O errors. ```APIDOC ## HttpWithResult API ### Description Allows sending HTTP requests and processing the results, including response bodies and potential network errors. ### Method `get(url: String, headers: Map[String, List[String]])` `post(url: String, headers: Map[String, List[String]], body: String)` `put(url: String, headers: Map[String, List[String]], body: String)` ### Endpoint N/A (This is an effect, not a network endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body For `post` and `put` methods, a `String` representing the request body. ### Request Example ```flix HttpWithResult.get("http://example.com/", Map.empty()) ``` ### Response #### Success Response (Result.Ok) Contains an `Http.Response` object upon successful request. #### Error Response (Result.Err) Contains an `IoError` if the HTTP request failed. #### Response Example ```flix Result.Ok(Http.Response { status_code = 200, headers = ..., body = "..." }) // or Result.Err(IoError("Connection refused")) ``` ``` -------------------------------- ### Flix 'Hello World' Program Source: https://doc.flix.dev/hello-world A basic 'Hello World' program in Flix. It demonstrates the syntax for defining a main function and printing output to the console. The main function in Flix has no formal parameters and returns Unit with the IO effect. ```flix __ def main(): Unit IO = println("Hello World!") ``` -------------------------------- ### Check Neovim Version Source: https://doc.flix.dev/print This command-line snippet demonstrates how to check the installed Neovim version. The official Flix plugin for Neovim requires version 0.11 or later. ```bash nvim --version ``` -------------------------------- ### Flix Accessing Command Line Arguments Source: https://doc.flix.dev/hello-world Demonstrates how to retrieve command-line arguments in a Flix program. This is achieved by calling the `Environment.getArgs` function, as Flix's main function does not accept arguments directly. ```flix import Environment def main(): Unit IO = let args = Environment.getArgs() println("Command line arguments: " + args) ``` -------------------------------- ### Example: Using Logger in Flix Source: https://doc.flix.dev/library-effects Demonstrates how to use the Logger effect to log messages at info and warn levels. ```flix def main(): Unit \ IO = run { Logger.info("Hello"); Logger.warn("World") } with Logger.runWithIO ``` -------------------------------- ### Compute Array Length Source: https://doc.flix.dev/arrays Shows how to find the number of elements in an array using the Array.length function. This is a straightforward way to get the size of an array. ```rc region rc { let fruits = Array#{"Apple", "Pear", "Mango"} @ rc; println(Array.length(fruits)) } ``` -------------------------------- ### Flix Kind Ascription for Traits Source: https://doc.flix.dev/print Demonstrates how kind ascriptions are applied to traits in Flix. This example defines a trait `MyTrait` with a type parameter `t` that is required to have the kind `Type`. ```flix trait MyTrait[t: Type] { // ... } ``` -------------------------------- ### Select with a Default Case to Avoid Blocking Source: https://doc.flix.dev/print Shows how to use a `select` expression with a default case to avoid blocking indefinitely when no message is immediately available on any channel. This example demonstrates selecting a default value if messages are not received from the specified channels. It requires the `Chan` and `NonDet` effects. ```source 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" } } ``` -------------------------------- ### Extending Java Classes in Flix Source: https://doc.flix.dev/print Shows how to create Flix objects that extend Java classes and override methods. This example extends java.lang.Object and overrides 'hashCode' and 'toString'. ```flix def newObject(): Object IO = new Object { def hashCode(_this: Object): Int32 = 42 def toString(_this: Object): String = "Hello World!" } ``` -------------------------------- ### Using Clock to Get Current Time in Flix Source: https://doc.flix.dev/print Demonstrates how to retrieve the current timestamp in milliseconds since the epoch using the `Clock` effect in Flix. This requires the `Clock.runWithIO` context. ```flix __ def main(): Unit \ IO = run { let timestamp = Clock.currentTime(TimeUnit.Milliseconds); println("${timestamp} ms since the epoc") } with Clock.runWithIO ``` -------------------------------- ### Grouped Use Declarations in Flix Source: https://doc.flix.dev/print Demonstrates how to group multiple `use` declarations for functions within a module into a single, more concise statement. This improves readability by reducing repetitive `use` lines. ```flix mod Math { pub def sum(x: Int32, y: Int32): Int32 = x + y pub def mul(x: Int32, y: Int32): Int32 = x * y } use Math.{sum, mul}; def main(): Unit \ IO = mul(42, 84) |> sum(21) |> println ``` -------------------------------- ### Accessing Java Static Inner Classes in Flix Source: https://doc.flix.dev/print Explains how to access static inner classes of Java classes in Flix using the 'import' statement with a '$' separator. This example accesses Foo.Bar.OuterClass.StaticInnerClass. ```flix import Foo.Bar.{OuterClass$StaticInnerClass => Inner} def main(): Unit IO = println(Inner.hello()) ``` -------------------------------- ### Defining and Using Traits in Flix Modules Source: https://doc.flix.dev/print Demonstrates defining a trait within a module and implementing it for a type. It shows how to use fully-qualified names or `use` declarations to access the trait and its methods. ```flix mod Zoo { pub trait Speakable[t] { pub def say(x: t): String } } enum Animal with ToString { case Cat, case Dog, case Fox } instance Zoo.Speakable[Animal] { pub def say(a: Animal): String = match a { case Cat => "Meow" case Dog => "Woof" case Fox => "Roar" } } use Zoo.Speakable use Zoo.Speakable.say def speak(x: t): Unit \ IO with Speakable[t], ToString[t] = println("A ${x} says ${say(x)}!") def main(): Unit \ IO = speak(Animal.Cat) ``` -------------------------------- ### Polymorphic Records in Flix Source: https://doc.flix.dev/index Illustrates the concept of polymorphic records in Flix, where functions can operate on records with a guaranteed set of fields while allowing additional fields. This example calculates areas of records. ```flix /// Returns the area of the polymorphic record `r`. /// Note that the use of the type variable `a` permits the record `r` /// to have labels other than `x` and `y`. def polyArea[a : RecordRow](r: {x = Int32, y = Int32 | a}): Int32 = r#x * r#y /// Computes the area of various rectangle records. /// Note that some records have additional labels. def polyAreas(): List[Int32] = polyArea({x = 1, y = 2}) :: polyArea({x = 2, y = 3, z = 4}) :: Nil def main(): Unit \ IO = polyAreas() |> println ``` -------------------------------- ### Spawn a Process with IO in Flix Source: https://doc.flix.dev/print Illustrates spawning a concurrent process using the 'spawn' keyword in Flix. The process is associated with a region 'rc' and performs an IO action (printing to the console). ```flix def main(): Unit \ IO = region rc { spawn println("Hello from thread") @ rc; println("Hello from main") } ``` -------------------------------- ### Flix String Interpolation Example Source: https://doc.flix.dev/essential-traits Demonstrates Flix's string interpolation syntax and its underlying expansion using the ToString trait. ```flix __ "Good morning ${name}, it is ${hour} o'clock." ``` ```flix __ "Good morning " + ToString.toString(name) + ", it is " + ToString.toString(hour) + " o'clock." ```