Baseline: tree as shared

This commit is contained in:
alexm committed 2026-10-05 03:03:38 +00:00
commit 31f2fb8a5a
1679 files changed
+1024562

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Every Mojo program must include a function named `main()` as the entry point
def boot():
print("MQ Robotics control daemon starting")
def main():
boot()
+15
View File
@@ -0,0 +1,15 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Code blocks such as functions, conditions, and loops are defined with a colon followed by indented lines
def main():
print("MQ Robotics nav stack online")
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Mojo uses the `def` keyword to define functions
def heartbeat() -> String:
return "heartbeat ok"
def main():
print(heartbeat())
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: You must declare the type of each function parameter and argument; the return type follows `->`
def grid_cells(rows: Int, cols: Int) -> Int:
return rows * cols
def main():
print("Grid cells:", grid_cells(3, 4))
+22
View File
@@ -0,0 +1,22 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Values are passed back using the `return` keyword; the return type is declared with the `-> type` syntax
# Ring-buffer helpers for the sensor ingest loop
def grow_capacity(n: Int) -> Int:
return n * 2
def main():
print("New capacity:", grow_capacity(21))
+20
View File
@@ -0,0 +1,20 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: A docstring is a string literal in triple quotes placed as the first statement in a function body
def log_command(name: String) -> String:
"""Return a log line announcing the command being dispatched."""
return "Dispatching command: " + name
def main():
print(log_command("rotate-90"))
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Keyword arguments are specified using `argument_name = argument_value` and can be passed in any order
def set_limits(max_speed: Int, max_accel: Int):
print("speed:", max_speed, "accel:", max_accel)
def main():
set_limits(max_speed=2, max_accel=5)
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: An optional argument includes a default value, and must appear after any required arguments
def spin_up(rpm: Int, ramp_ms: Int = 100) -> Int:
return rpm + ramp_ms
def main():
print("total:", spin_up(900))
+21
View File
@@ -0,0 +1,21 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: A single star (`*`) in the argument list marks the following arguments as keyword-only
def run_diagnostic(name: String, *, verbose: Bool) -> String:
if verbose:
return name + " [verbose]"
return name
def main():
print(run_diagnostic("imu", verbose=True))
+22
View File
@@ -0,0 +1,22 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Use the variadic argument syntax `*argument_name` to accept a variable number of arguments
def total(*readings: Int) -> Int:
var s = 0
for r in readings:
s += r
return s
def main():
print("sum:", total(3, 4, 5))
+21
View File
@@ -0,0 +1,21 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Use `pass` as a no-op placeholder when a block requires a body but has nothing to do
def run_self_test():
# TODO: implement the real self-test later; this is just a stub
pass
def main():
run_self_test()
print("self-test stub ran")
+23
View File
@@ -0,0 +1,23 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Implement separate versions of a function with different argument types to "overload" it
def footprint(side: Int) -> Int:
return side * side
def footprint(w: Int, h: Int) -> Int:
return w * h
def main():
print(footprint(4), footprint(2, 3))
+21
View File
@@ -0,0 +1,21 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Functions are non-raising by default; add the `raises` keyword to propagate an error to the caller
def read_sensor(id: Int) raises -> Int:
if id < 0:
raise Error("bad sensor id")
return id * 10
def main() raises:
print("reading:", read_sensor(2))
+17
View File
@@ -0,0 +1,17 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Explicitly-declared variables are created with the `var` keyword
def main():
var tick_count = 0
tick_count += 1
print("Ticks processed:", tick_count)
+17
View File
@@ -0,0 +1,17 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Late initialization works only if the variable is declared with a type
def main():
var threshold: Int
threshold = 10
print("threshold:", threshold)
+16
View File
@@ -0,0 +1,16 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Since variables are strongly typed, you can't assign a value of a different type
def main():
var count: Int = 5
print("count:", count)
+18
View File
@@ -0,0 +1,18 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: A variable owns its value; ownership is transferred with the `^` sigil, which leaves the source uninitialized
def main():
var a: List[Int] = [1, 2, 3]
var b = a.copy()
a.append(4)
print("a:", len(a), "b:", len(b))
+18
View File
@@ -0,0 +1,18 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Use the `ref name` syntax to bind a reference to a value rather than an owned copy
def main():
var readings: List[Int] = [10, 20, 30]
ref first = readings[0]
first = 99
print("first:", readings[0])
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Numeric operators don't automatically narrow or widen operands to a common type
def widen_add(reading: Int8, total: Int64) -> Int64:
return Int64(reading) + total
def main():
print("total:", widen_add(100, 1000))
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Convert the operands to the target type's constructor before dividing to avoid integer truncation
def avg_latency(total_ms: Int, num_loops: Int) -> Float64:
return Float64(total_ms) / Float64(num_loops)
def main():
print("avg latency:", avg_latency(7, 2))
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: A `SIMD` value is a fixed-size vector defined by two parameters: a `DType` and the number of elements
comptime Velocity = SIMD[.float32, 4]
def main():
var v = Velocity(1.0, 2.0, 3.0, 4.0)
print("Velocity lane 0:", v[0])
+21
View File
@@ -0,0 +1,21 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Math operations on SIMD values are applied elementwise, on each individual element in the vector
def combine_counts(a: SIMD[.int32, 4], b: SIMD[.int32, 4]) -> SIMD[.int32, 4]:
return a + b
def main():
var imu_a = SIMD[.int32, 4](1, 2, 3, 4)
var imu_b = SIMD[.int32, 4](10, 20, 30, 40)
print("Combined counts:", combine_counts(imu_a, imu_b))
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: `String` supports a variety of operators and common methods, such as `upper()`
def device_tag(family: String, model: String) -> String:
return (family + "-" + model).upper()
def main():
print(device_tag("mq", "amr"))
+18
View File
@@ -0,0 +1,18 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Index a `List` with `list[i]` to read an element; assign to `list[i]` to replace it in place
def main():
var path: List[Int] = [10, 20, 30]
path[0] = 15
print("first waypoint:", path[0])
print("waypoints:", len(path))
+25
View File
@@ -0,0 +1,25 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: A `Tuple` is an ordered collection; unpack it or index it to get individual values
def scan_stats() -> Tuple[Int, Int]:
var num_scans = 4
var total_points = 512
return (num_scans, total_points)
def main():
var stats = scan_stats()
var scans = stats[0]
var points = stats[1]
print("scans:", scans)
print("points:", points)
+18
View File
@@ -0,0 +1,18 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: A given `List` can only hold one type of value, specified at compile time as a parameter
def main():
var waypoints = List[Int]()
waypoints.append(128)
waypoints.append(256)
print("Queued waypoints:", len(waypoints))
+22
View File
@@ -0,0 +1,22 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: `Dict` holds key-value pairs; specify the key type and value type as parameters
from std.collections import Dict
def main() raises:
var joint_angles = Dict[String, Int]()
joint_angles["joint_3"] = 128
joint_angles["joint_8"] = 256
print("joint angle:", joint_angles["joint_3"])
print("joints:", len(joint_angles))
+22
View File
@@ -0,0 +1,22 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: `Set` represents a collection of unique values
from std.collections import Set
def main():
var seen = Set[Int]()
seen.add(1)
seen.add(1)
seen.add(2)
print("unique:", len(seen))
+33
View File
@@ -0,0 +1,33 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: An `Optional` represents a value that may or may not be present
from std.collections import Optional
def cache_lookup(sensor_id: Int) -> Optional[Int]:
if sensor_id == 7:
return 512
return None
def main() raises:
var hit = cache_lookup(7)
var miss = cache_lookup(3)
if hit:
print("hit:", hit.value())
else:
print("hit:", hit)
if miss:
print("miss:", miss.value())
else:
print("miss:", miss)
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Exponentiation uses two stars (`**`), not a caret
def square_area(side: Int) -> Int:
return side**2
def main():
print("area:", square_area(4))
+20
View File
@@ -0,0 +1,20 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Use `//` for floor division; the modulo operator `%` returns the remainder
def split_into_bins(total: Int, per_bin: Int) -> Tuple[Int, Int]:
return total // per_bin, total % per_bin
def main():
var result = split_into_bins(17, 5)
print("bins:", result[0], "left:", result[1])
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Mojo provides six comparison operators: `==`, `!=`, `<`, `<=`, `>`, and `>=`, each returning a `Bool`
def battery_low(level: Int) -> Bool:
return level <= 20
def main():
print("low:", battery_low(20))
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: You can chain comparisons; `a < b < c` is equivalent to `(a < b) and (b < c)`
def in_range(temp: Int) -> Bool:
return 0 <= temp <= 85
def main():
print("in range:", in_range(90))
+22
View File
@@ -0,0 +1,22 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Bitwise OR (`|`) keeps bits that are set in either operand
def status_word(ready: Int, armed: Int) -> Int:
return ready | armed
def main():
var READY = 1
var ARMED = 2
var flags = status_word(READY, ARMED)
print("armed:", (flags & ARMED) != 0)
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: With `and`, both operands must be truthy; if the left side is falsy, the right side isn't evaluated
def can_drive(has_fix: Bool, calibrated: Bool) -> Bool:
return has_fix and calibrated
def main():
print("go:", can_drive(True, False))
+20
View File
@@ -0,0 +1,20 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: The `in` operator checks whether a collection contains a value
def is_allowed(sensor_id: Int, allowed: List[Int]) -> Bool:
return sensor_id in allowed
def main():
var allowed: List[Int] = [2, 4, 6]
print("ok:", is_allowed(4, allowed))
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: A conditional expression has the form `value_if_true if condition else value_if_false`
def speed_label(speed: Int) -> String:
return "fast" if speed > 10 else "slow"
def main():
print("mode:", speed_label(12))
+17
View File
@@ -0,0 +1,17 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Compound assignment forms like `*=` update the left-hand value instead of creating a new one
def main():
var scale = 2
scale *= 3
print("scale:", scale)
+20
View File
@@ -0,0 +1,20 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Precedence determines what runs first (multiply before add); when in doubt, use parentheses
def path_cost(setup: Int, per_segment: Int, segments: Int) -> Int:
# setup plus per-segment cost, then multiplied across the segments
return (setup + per_segment) * segments
def main():
print("Total distance:", path_cost(2, 3, 4))
+23
View File
@@ -0,0 +1,23 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: The `if` statement executes an indented block when its boolean expression evaluates to `True`
def route_task(queue_depth: Int) -> String:
if queue_depth > 100:
return "overflow-core"
else:
return "fast-core"
def main():
print(route_task(250))
print(route_task(40))
+20
View File
@@ -0,0 +1,20 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: The `while` loop repeatedly executes a block while its boolean expression evaluates to `True`
def main():
var attempt = 1
var total = 0
while attempt <= 5:
total += attempt
attempt += 1
print("Retry budget:", total)
+20
View File
@@ -0,0 +1,20 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: In a `for` loop, `continue` skips the rest of the block and resumes with the next element
def main():
var total = 0
for i in range(1, 10):
if i % 3 == 0:
continue
total += i
print("Scheduled units:", total)
+26
View File
@@ -0,0 +1,26 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Use `elif` to add another condition to an `if`, checked only when the earlier branches were false
def power_mode(level: Int) -> String:
if level >= 80:
return "boost"
elif level >= 30:
return "cruise"
else:
return "sleep"
def main():
print(power_mode(95))
print(power_mode(50))
print(power_mode(10))
+18
View File
@@ -0,0 +1,18 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: A range is a sequence of integers generated by `range(start, stop, step)`
def main():
var total = 0
for i in range(0, 10, 2):
total += i
print("total:", total)
+18
View File
@@ -0,0 +1,18 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Add the `ref` keyword before the loop variable to bind a reference and mutate the collection in place
def main():
var readings: List[Int] = [1, 2, 3]
for ref r in readings:
r += 10
print("first:", readings[0])
+23
View File
@@ -0,0 +1,23 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: All collection types in the `collections` module support `for` loop iteration over each element
def total_points(batch: List[Int]) -> Int:
var total = 0
for count in batch:
total += count
return total
def main():
var batch: List[Int] = [12, 8, 20, 5]
print("total points:", total_points(batch))
+21
View File
@@ -0,0 +1,21 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: By declaring `raises`, you tell Mojo a function may raise an error; raise one with `raise Error("...")`
def validate_velocity(n: Int) raises -> Int:
if n <= 0:
raise Error("velocity must be positive")
return n
def main() raises:
print("Validated:", validate_velocity(256))
+24
View File
@@ -0,0 +1,24 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Mojo uses `try`/`except` to detect and handle errors
def checked(n: Int) raises -> Int:
if n < 0:
raise Error("negative reading")
return n
def main():
try:
print("value:", checked(-1))
except:
print("value: 0")
+26
View File
@@ -0,0 +1,26 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: To re-raise a caught error, use `raise` with the `^` sigil to transfer ownership of the error value
def attempt() raises:
try:
raise Error("sensor fault")
except e:
print("logging:", e)
raise e^
def main():
try:
attempt()
except:
print("recovered")
+20
View File
@@ -0,0 +1,20 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: A `with` statement context manager releases its resource at the end of the block, even if an error occurs
def main() raises:
# MQ Robotics stores the active calibration profile on disk.
with open("calib.txt", "w") as f:
f.write("max_speed=1.5")
with open("calib.txt", "r") as f:
print(f.read())
+28
View File
@@ -0,0 +1,28 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: All struct fields are declared with `var` and a type annotation, and must be initialized in the constructor
struct LidarScan(Copyable, Movable):
var near_points: Int
var far_points: Int
def __init__(out self, near_points: Int, far_points: Int):
self.near_points = near_points
self.far_points = far_points
def total(self) -> Int:
return self.near_points + self.far_points
def main():
var scan = LidarScan(8, 256)
print("Total points:", scan.total())
+26
View File
@@ -0,0 +1,26 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: An instance method takes `self` as an explicit first argument, letting it act on a particular instance of the struct
struct Battery:
var charge: Int
def __init__(out self, charge: Int):
self.charge = charge
def is_low(self) -> Bool:
return self.charge < 20
def main():
var b = Battery(15)
print("low:", b.is_low())
+31
View File
@@ -0,0 +1,31 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: To let a method mutate the instance, declare its receiver as `mut self`
struct FrameCounter(Copyable, Movable):
var count: Int
def __init__(out self, count: Int):
self.count = count
def increment(mut self):
self.count += 1
def get(self) -> Int:
return self.count
def main():
var counter = FrameCounter(0)
counter.increment()
counter.increment()
print("Frames handled:", counter.get())
+21
View File
@@ -0,0 +1,21 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: A `@staticmethod` can be called without an instance and doesn't receive `self`, so it can't access fields
struct Encoder:
@staticmethod
def ticks_per_rev() -> Int:
return 4096
def main():
print("ppr:", Encoder.ticks_per_rev())
+25
View File
@@ -0,0 +1,25 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: The `@fieldwise_init` decorator generates a field-wise constructor, so you don't have to write `__init__` by hand
@fieldwise_init
struct LidarScan(Copyable, Movable):
var near_points: Int
var far_points: Int
def total(self) -> Int:
return self.near_points + self.far_points
def main():
var scan = LidarScan(8, 256)
print("Total points:", scan.total())
+27
View File
@@ -0,0 +1,27 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: A move-only type is `Movable` but not `Copyable`; transfer it with the `^` sigil
struct FileHandle(Movable):
var fd: Int
def __init__(out self, fd: Int):
self.fd = fd
def take(var h: FileHandle) -> Int:
return h.fd
def main():
var h = FileHandle(3)
print("fd:", take(h^))
+28
View File
@@ -0,0 +1,28 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Mojo evaluates `a + b` by calling `a.__add__(b)`
struct EnergyBudget(Copyable, Movable):
var millijoules: Int
def __init__(out self, millijoules: Int):
self.millijoules = millijoules
def __add__(self, other: Self) -> Self:
return Self(self.millijoules + other.millijoules)
def main():
var drive_budget = EnergyBudget(100)
var sense_budget = EnergyBudget(56)
var total = drive_budget + sense_budget
print("combined budget:", total.millijoules)
+27
View File
@@ -0,0 +1,27 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: A unary operator like `-x` calls `__neg__()`, returning a new value representing the result
struct Offset(Copyable, Movable):
var v: Int
def __init__(out self, v: Int):
self.v = v
def __neg__(self) -> Self:
return Self(-self.v)
def main():
var o = Offset(5)
var n = -o
print("neg:", n.v)
+27
View File
@@ -0,0 +1,27 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Implement `__eq__()` to support `==`; the `Equatable` trait provides `__eq__()` and `__ne__()`
struct Version(Copyable, Movable):
var major: Int
def __init__(out self, major: Int):
self.major = major
def __eq__(self, other: Self) -> Bool:
return self.major == other.major
def main():
var a = Version(2)
var b = Version(2)
print("equal:", a == b)
+34
View File
@@ -0,0 +1,34 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Implement `__getitem__()` to support subscript reads (`obj[i]`)
struct Frame(Copyable, Movable):
var a: Int
var b: Int
var c: Int
def __init__(out self, a: Int, b: Int, c: Int):
self.a = a
self.b = b
self.c = c
def __getitem__(self, i: Int) -> Int:
if i == 0:
return self.a
if i == 1:
return self.b
return self.c
def main():
var f = Frame(10, 20, 30)
print("channel 1:", f[1])
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: `from module import name` imports a specific member from a module
from std.math import sqrt
def main():
var root = sqrt(144.0)
print("Square root:", root)
+22
View File
@@ -0,0 +1,22 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Arguments are read-only by default; the `mut` convention lets the function write back to the caller's value
def record_sample(mut total: Int, sample: Int):
total += sample
def main():
var total = 0
record_sample(total, 12)
record_sample(total, 8)
print("Total distance:", total)
+21
View File
@@ -0,0 +1,21 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: The `^` transfer sigil ends a variable's lifetime and transfers ownership into a `var` argument
def load_map(var cells: List[Int]) -> Int:
return len(cells)
def main():
var cells: List[Int] = [16, 32, 64, 128]
var result = load_map(cells^)
print("map cells loaded:", result)
+28
View File
@@ -0,0 +1,28 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: A `ref` return value must name an origin; it returns a reference to an existing value, not a copy
struct CommandQueue(Copyable, Movable):
var depth: Int
def __init__(out self, depth: Int):
self.depth = depth
def borrow_depth(ref self) -> ref[self.depth] Int:
return self.depth
def main():
var q = CommandQueue(4)
ref d = q.borrow_depth()
d = 10
print("queue depth:", q.depth)
+25
View File
@@ -0,0 +1,25 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: By the end of a constructor, all of the struct's fields must be initialized
struct Waypoint(Copyable, Movable):
var x: Int
var y: Int
def __init__(out self, x: Int, y: Int):
self.x = x
self.y = y
def main():
var w = Waypoint(3, 7)
print("y:", w.y)
+33
View File
@@ -0,0 +1,33 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Like any method, `__init__()` can be overloaded to construct the object from different arguments
struct RobotConfig(Copyable, Movable):
var name: String
var max_rate: Int
def __init__(out self, name: String, max_rate: Int):
self.name = name
self.max_rate = max_rate
# Re-badge an existing config under a new name, keeping its rate. This takes
# a different second-argument type than the constructor above, so it must be
# a separate overload — a default argument couldn't express both forms.
def __init__(out self, name: String, template: Self):
self.name = name
self.max_rate = template.max_rate
def main():
var base = RobotConfig("base", 512)
var arm = RobotConfig("arm", base)
print("Robot:", arm.name, "max_rate:", arm.max_rate)
+27
View File
@@ -0,0 +1,27 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: An `@implicit` single-argument constructor enables implicit conversion from the source type
struct Celsius(Copyable, Movable):
var deg: Int
@implicit
def __init__(out self, deg: Int):
self.deg = deg
def report(t: Celsius):
print("temp:", t.deg)
def main():
report(25)
+33
View File
@@ -0,0 +1,33 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Conforming to `Copyable` gives a type a compiler-synthesized `.copy()` method
struct ScanBuffer(Copyable):
var samples: List[Int]
def __init__(out self, var samples: List[Int]):
self.samples = samples^
def push(mut self, t: Int):
self.samples.append(t)
def size(self) -> Int:
return len(self.samples)
def main():
var original: List[Int] = [1, 2, 3]
var snapshot = ScanBuffer(original^)
var working = snapshot.copy()
working.push(99)
print("snapshot size:", snapshot.size())
print("working size:", working.size())
+24
View File
@@ -0,0 +1,24 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: The `ImplicitlyCopyable` trait lets the compiler copy a value on a plain assignment (`var b = a`)
struct Reading(ImplicitlyCopyable, Movable):
var v: Int
def __init__(out self, v: Int):
self.v = v
def main():
var a = Reading(5)
var b = a
print("a:", a.v, "b:", b.v)
+32
View File
@@ -0,0 +1,32 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Mojo calls a value's `__deinit__()` destructor when its lifetime ends (ASAP, last-use destruction)
struct MotorHandle:
var motor_id: Int
def __init__(out self, motor_id: Int):
self.motor_id = motor_id
print("Acquired motor", self.motor_id)
def __deinit__(deinit self):
print("Released motor", self.motor_id)
def drive():
var handle = MotorHandle(0)
print("Driving with motor", handle.motor_id)
def main():
drive()
print("Scheduler idle")
+16
View File
@@ -0,0 +1,16 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Assign an expression to a compile-time constant with `comptime`, which evaluates it once at compile time
def main():
comptime tick_budget = 50 * 20
print("tick budget:", tick_budget)
+21
View File
@@ -0,0 +1,21 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: `comptime for` fully unrolls a loop at compile time over a compile-time sequence like `range(LIMIT)`
comptime NUM_AXES = 4
def main():
var total = 0
comptime for i in range(NUM_AXES):
total += i
print("axis sum:", total)
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Parameters in `[]` are compile-time inputs; arguments in `()` are run-time values
def scale[factor: Int](x: Int) -> Int:
return x * factor
def main():
print("Scaled:", scale[3](14))
+25
View File
@@ -0,0 +1,25 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: A parameterized struct adds compile-time parameters in `[]` after its name; they are accessible on instances (e.g. `b.size`)
struct Buffer[size: Int](Copyable, Movable):
def __init__(out self):
pass
def capacity(self) -> Int:
return Self.size
def main():
var b = Buffer[8]()
print("capacity:", b.capacity())
print("size:", b.size)
+34
View File
@@ -0,0 +1,34 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Declare trait conformance in parentheses after the struct name; the compiler enforces the trait's requirements
trait Sensor:
def read(self) -> String:
...
struct Lidar(Sensor):
var name: String
def __init__(out self, name: String):
self.name = name
def read(self) -> String:
return "Reading from " + self.name
def announce[T: Sensor](sensor: T):
print(sensor.read())
def main():
announce(Lidar("lidar-front"))
+32
View File
@@ -0,0 +1,32 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: A trait can include a default method implementation that conforming structs inherit unless they override it
trait Greeter:
def name(self) -> String:
...
def greet(self) -> String:
return "hello " + self.name()
struct Robot(Greeter):
def __init__(out self):
pass
def name(self) -> String:
return "amr"
def main():
var r = Robot()
print(r.greet())
+28
View File
@@ -0,0 +1,28 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: The `Sized` trait requires a type to implement `__len__()`, which the built-in `len()` function uses
struct Track(Sized):
var name: String
var waypoints: List[Int]
def __init__(out self, name: String, var waypoints: List[Int]):
self.name = name
self.waypoints = waypoints^
def __len__(self) -> Int:
return len(self.waypoints)
def main():
var t = Track("loop-a", [10, 20, 30, 40, 50])
print("len:", len(t))
+21
View File
@@ -0,0 +1,21 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: `Some[Trait]` is shorthand for a trait-constrained generic parameter; `def f(v: Some[Writable])` is equivalent to `def f[T: Writable](v: T)`
# Logs any value the telemetry bus touches, whatever its type.
def log_value(value: Some[Writable]):
print("telemetry:", value)
def main():
log_value(42)
log_value("ready")
+21
View File
@@ -0,0 +1,21 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: `comptime assert cond, "msg"` asserts a condition at compile time; if false, compilation fails
def make_drive[num_motors: Int]() -> Int:
# The drive train must pair motors across an even motor count.
comptime assert num_motors % 2 == 0, "num_motors must be even"
return num_motors * 64
def main():
print("Drive slots:", make_drive[8]())
+23
View File
@@ -0,0 +1,23 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: The `comptime` keyword forces an expression to be evaluated at compile time
comptime dim = 8
def transform_size[dim: Int]() -> Int:
# a dim x dim transform matrix has dim * dim entries
return dim * dim
def main():
print("matrix entries:", transform_size[dim]())
+27
View File
@@ -0,0 +1,27 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Use `reflect[T]` to inspect a type at compile time, querying members like `field_count()`
struct RobotConfig(Copyable, Movable):
var max_speed: Int
var wheel_radius: Int
var num_sensors: Int
def __init__(out self, max_speed: Int, wheel_radius: Int, num_sensors: Int):
self.max_speed = max_speed
self.wheel_radius = wheel_radius
self.num_sensors = num_sensors
def main():
comptime field_count = reflect[RobotConfig].field_count()
print("RobotConfig fields:", field_count)
+24
View File
@@ -0,0 +1,24 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: Use the free function `unsafe_alloc[T](n)` to allocate space for `n` uninitialized values of `T`
from std.memory.alloc import unsafe_alloc
def main():
# Stage a single encoder reading in a scratch buffer.
var ptr = unsafe_alloc[Int](1)
ptr.unsafe_write(copy=99)
var value = ptr[]
print("Encoder count:", value)
ptr.unsafe_deinit_pointee()
ptr.unsafe_free()
+19
View File
@@ -0,0 +1,19 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: With space for multiple values, `ptr[unsafe_offset=i]` accesses the element at offset `i`
def main():
var ptr = alloc[Int]({count = 2}).unsafe_leak()
ptr[unsafe_offset=0] = 10
ptr[unsafe_offset=1] = 20
print("second:", ptr[unsafe_offset=1])
ptr.unsafe_free()
+23
View File
@@ -0,0 +1,23 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: `assert_equal` from the `testing` module asserts that two values are equal
from std.testing import assert_equal
def total_distance(near: Int, far: Int) -> Int:
return near + far
def main() raises:
assert_equal(total_distance(100, 50), 150)
print("All checks passed!")
+26
View File
@@ -0,0 +1,26 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Mojo concept: `assert_raises` from the `testing` module is a context manager that asserts its `with` block raises an error
from std.testing import assert_raises
def clamp(n: Int) raises -> Int:
if n < 0:
raise Error("negative speed")
return n
def main() raises:
with assert_raises():
_ = clamp(-1)
print("raised as expected")