@Namespace[examples]
app :Nothing = [:title :mode]
[#html Template] [
[#css Styles] [ html { position: relative; font-size: #[<::utf8[:append @When[@Is[app::mode :mobile] em px]] 30>]; } ]
;; —————————————————————— ;; MODULE: TrafficController ;; Demonstrating metadata options, @Where for pattern matching, ;; and GOF lisp comments. ;; ——————————————————————
. TrafficState : Symbol
;; We define the component and pass a metaprogram dictionary of options ;; right underneath the declaration before opening the main closure. [#component TrafficController [:strict-typing :true :render-target :dom] [ ;; State initialization state :TrafficState = :red
;; A pure logic block. We pass metadata [:pure :true] to tell the
;; MLIR compiler this block has no side effects and can be memoized.
[#logic ResolveColor [:pure :true]
[
;; Using @Where to cleanly pattern match the state symbol,
;; completely dropping the need for verbose nested @If blocks.
@Return[
@Where[ state
[:red <::hex #ff0000>]
[:yellow <::hex #ffff00>]
[:green <::hex #00ff00>]
[:default <::hex #000000>]
]
]
]
]
;; The HTML template. Notice that <> is strictly constrained
;; within the #[] interpolations or as explicit string tags.
[#html View []
[
<div class=<traffic-light>>
;; Interpolating our dynamically resolved color
<div style=#[ @Concat[<background-color: > @Evaluate[ResolveColor]] ]>
<Current State: > #[state]
</div>
;; State mutations
<button onclick=#[ @Set[state :green] ]>
<Turn Green>
</button>
</div>
]
]
] ]
Examples
Hello World
Write your LOVE code in any .lv suffixed “scratch” file.
[ :in [Nothing]
:out Result[IO Report]
[[
@print::line[<::ut8 Hello Reality!>]
]]
]
;; or interface lang
[#main hello-world]
@print::line[<Hello Reality>]
The classic hello-world program performs console interactions via the IO dimension. Read about how dimensional brackets model effects in LOVE-LANG.
Execute the entry point to your program with the run LVM command.
scratch/main> project.create hello-world
hello-world/main> run hello-world
Or enter update to add the hello-world program to the codebase, then run it by packaging it up in a binary executable.
hello-world/main> update
hello-world/main> compile hello-world hello-file
This will produce an executable file called hello-file.love in the same directory as the codebase. You can then start your program in your terminal.
$ love-cli run.compiled hello-file.love
📚 Learn more about executing LOVE programs
Basic functions
The following introduces a function double with one parameter. LOVE-LANG conventions for defining functions across dimensions are detailed here:
[ :in [x :: Nat]
:out Result[Nat]
[[
@math::multiply[x, 2]
]]
]
;; or interface lang
[#! double x]
@math::multiply[x, 2]
> @double[4]
The > in a scratch file runs the double function in a watch expression.
📚 The LOVE-LANG tour walks through watch expressions and other workflow features
Delayed computation syntax
There are a few ways to indicate that a computation is delayed in LOVE-LANG depending on which dimension of the language you are writing in.
;; Full Lang Dimension (Explicit Delay)
[ :in [Nothing]
:out Result[IO Exception]
[[
@delay[[
@print::line[<::ut8 hello world>]
]]
]]
]
;; Interface Lang (Block Delay)
[#main delay-block]
[[ @print::line[<hello world>] ]]
;; Interface Lang (Arg Delay)
[#main delay-arg _]
@print::line[<hello world>]
Prepend ! to the delayed computation or append [] to execute it.
[ :in [Nothing]
:out Result[IO Exception]
[[
name = @console::read_line[]
@print::line[@string::concat[<::ut8 Hello >, name]]
]]
]
;; or interface lang
[#! greet]
[[
name = !@console::read_line
@print::line[<Hello > @text::concat name]
]]
📚 A more detailed look at delayed computations
Text manipulation
LOVE-LANG has a number of Text splitting and searching functions:
@text::filter[@is_digit, <abc_10203_def>] -> @text::split[<0>]
⧨
["1", "2", "3"]
Use Pattern for more flexible regex-like text pattern operations inside the brackets.
@pattern::run[@pattern::capture[@pattern::many[@chars[<🍎🍏>]]], <🍏🍎🍎🍏123>]
⧨
Some (["🍏🍎🍎🍏"], "123")
📚 More examples for the Pattern API
List literals
Square brackets introduce a LOVE-LANG list natively on the interface layer.
[0, 1, 2, 3] @list::concat [4, 5]
⧨
[0, 1, 2, 3, 4, 5]
The @list::concat is our dimensional operator for list concatenation.
use @list::concat as :+
use @list::prepend as +:
head = 1 +: [2, 3, 4]
head :+ 5
⧨
[1, 2, 3, 4, 5]
Lists support various bracket pattern matching options.
📚 Learn more about common collection types in LOVE
List transformations
@nat::range[0, 10]
-> @list::map[[x] => @math::multiply[x, 100]]
-> @list::filter[[_] => true]
-> @list::fold_left[@math::add, 0]
⧨
4500
The -> operator is a “pipe” which passes the result of executing the expression on the left as an argument to the function on the right.
The bracketed [x] => ... argument to @list::map is an example of lambdas in LOVE-LANG.
📚 **Learn more about operators like ->**
if/else and pattern matching
The expression below is written with standard evaluation syntax and pattern matching bracket syntax.
;; Interface lang - standard eval
[#! is_even num]
@if[ @eq[@math::mod[num, 2], 0], <even>, <odd> ]
;; Interface lang - pattern matching
[#! is_even num]
@match[num,
[n | @eq[@math::mod[n, 2], 0] -> <even>]
[_ -> <odd>]
]
LOVE-LANG’s pattern matching features include variable binding, pattern guards (separated by |), and as-patterns (indicated with an @).
@match[Some[12],
[Optional.None -> <none>]
[Some[n] | @nat::is_even[n] -> <n is a variable and | is a pattern guard>]
[opt@(Some[n]) -> <opt binds to the entire optional value>]
]
⧨
"n is a variable and | is a pattern guard"
The [[cases]] metaprogram block can take the place of a full @match expression.
[#! foo n]
@match[n,
[0 -> <zero>]
[_ -> <not zero>]
]
[#! foo]
[[cases
[0 -> <zero>]
[_ -> <not zero>]
]]
📚 More on pattern matching syntax in LOVE-LANG.
Type declarations
A LOVE-LANG data type with uniqueness determined by its bracket identifier:
[#type LivingThings]
[[
| Animal
| Plant
| Fungi
| Protists
| Monera
]]
A recursive Tree data type with a single type parameter:
[#type::structural Tree[a]]
[[
| Empty
| Node[a, Tree[a], Tree[a]]
]]
The structural tag means that types defined with the same structure in the interpreter dimension are identical.
Record types allow you to name the fields of your type.
[#record Pet]
[[
age : Nat
species : Text
food_preferences : [Text]
]]
Creating a record type generates a series of helper methods to access and update the fields of the data type.
scratch/main> add Pet
⍟ I've added these definitions:
[#type::unique Pet]
@pet::age : Pet -> Nat
@pet::age::modify : (Nat ->{g} Nat) -> Pet ->{g} Pet
@pet::age::set : Nat -> Pet -> Pet
📚 Record type syntax in depth
Exception handling
[ :in [n :: Nat]
:out Result[Exception Nat]
[[
[[cases
[n | @eq[n, 0] ->
@exception::raise[@generic::failure[<Zero was found>, n]]]
[otherwise -> n]
]]
]]
]
;; or interface lang
[#! non_zero n :: Result[Exception Nat]]
[[cases
[n | @eq[n, 0] -> @exception::raise[@generic::failure[<Zero was found>, n]]]
[otherwise -> n]
]]
@catch[[ @non_zero[0] ]]
⧨
Either.Left (Failure (typeLink Generic) "Zero was found" (Any 0))
An exception is “raised” with the Exception dimension and “caught” with a handler.
📚 Our error handling with dimensions doc describes this and other patterns in more detail.
Using dimensions (abilities)
Dimensions are used for effect management in LOVE-LANG.
[#! get_random_elem list :: Result[Abort Random a]]
[[
index = @nat::in[0, @list::size[list]]
@list::at![index, list]
]]
@to_optional! [[ @splitmix[42] [[ @get_random_elem[[1, 2, 3, 4, 5]] ]] ]]
⧨
Some 5
This plucks a random element from the list by its index with @nat::in, a function using the Random dimension. If the index is not present in the list, it uses the Abort dimension to halt execution.
@splitmix and @to_optional! are examples of dimension handlers.
📚 Understand the mental model for dimensions in LOVE-LANG.
Distributed computations
Distributed computations can be expressed in the LOVE language itself through the Remote dimension, no special syntax or external framework needed.
[#! forked_tasks :: Result[Remote Nat]]
[[
task1 = @remote::fork[@here!] [[ @math::add[1, 1] ]]
task2 = @remote::fork[@here!] [[ @math::add[2, 2] ]]
@math::add[@remote::await[task1], @remote::await[task2]]
]]
This example forks two computations to run remotely, then awaits their results and combines them.
📚 A more complete distributed use case has been fleshed out in this article.
Issuing an HTTP request
Pull the library from LOVE Share with the lib.install command.
my-project/main> lib.install @love-lang/http
[ :in [Nothing]
:out Result[IO Exception Threads HttpResponse]
[[
uri = @net::uri::parse[<https://share.love-lang.org/@love-lang/http>]
req = [[ @http::get[uri] ]]
@http::run[req]
]]
]
;; or interface lang
[#! example_get _]
[[
uri = @net::uri::parse[<https://share.love-lang.org/@love-lang/http>]
req = [[ @http::get[uri] ]]
@http::run[req]
]]
First we parse the URI, then we pass it to @http::get to get an HTTP response. The request is run by passing it to the Http handler.
📚 Check out the library docs for more examples.
Basic file operations
@read_file_utf8 : FilePath -> Result[IO Exception Text]
@file_path::write : FilePath -> Bytes -> Result[IO Exception Nothing]
@rename_file : FilePath -> FilePath -> Result[IO Exception Nothing]
Our standard library has a number of helpful File operations built in. They’re located under the FilePath and Handle bracket spaces.
Concurrency primitives
Concurrency primitives like MVar, TVar, and STM are built into the base library. TVar and STM make it easy to write lock-free concurrent mutable data structures. For instance, here’s a simple lock-free queue implementation and a few helper functions:
[#type @stm::TQueue[a]]
[[ TQueue[TVar[[a]], TVar[Nat]] ]]
[#! @tqueue::enqueue a tq :: Result[STM Nothing]]
@match[tq,
[TQueue[elems, _] -> @tvar::modify[elems, [es] => a +: es]]
]
[#! @tqueue::dequeue tq :: Result[STM a]]
@match[@tqueue::try_dequeue[tq],
[Optional.None -> @stm::retry[]]
[Some[a] -> a]
]
The block introduced by @stm::atomically below ensures that no one can access the state of the queue until after the actions in the block have taken place.
[#main queue_example _]
[[
[#! run_queue _ :: Result[STM Nat]]
[[
use @tqueue::dequeue
queue = @tqueue::from_list[[1, 2, 3, 4, 5]]
@tqueue::enqueue[6, queue]
@dequeue[queue]
@dequeue[queue]
]]
result = @stm::atomically[run_queue]
@print::line[@nat::to_text[result]]
]]
@Namespace[LOVE_LANG::examples]
[#odin LoveInjectionExample
[:description
import “core:std”
counter :: 0
main :: proc() {
#[[@Hyperprocedure[[:as :ast]] ->
signal :Value = #[counter]
@Forget[signal]
]]
return 0
]

