MufiZ

Mufi Lang with Ziggyness

A powerful programming language that integrates the Mufi-Lang compiler with Zig, utilizing Zig's build system for easy cross-compatibility, and enhanced memory safety.

Latest: v0.10.0 "Echo" Zig v0.15.2

Features

🚀 Cross-Platform

Built with Zig's build system for easy cross-compatibility and efficient caching across different platforms.

🔒 Memory Safe

Enhanced memory safety through integration with Zig's memory management capabilities.

📚 Rich Standard Library

Comprehensive standard library with modules for math, collections, networking, file system operations, and more.

âš¡ SIMD Optimizations

Advanced SIMD optimizations for high-performance string operations and mathematical computations.

🔧 Interactive REPL

Enhanced interactive shell with improved input handling and cleaner user experience.

🎯 Matrix Operations

Built-in support for matrix operations including linear algebra functions.

Installation

MufiZUp Unix Install

One-Line Install

curl -fsSL https://install.mufi-lang.org/installer.sh | sudo sh -s install

Visit install.mufi-lang.org for more information.

Package Managers

Homebrew (macOS/Linux)

brew tap Mustafif/homebrew-mufi
brew install mufiz

Scoop (Windows)

scoop bucket add mufi-bucket https://github.com/Mustafif/mufi-bucket
scoop install mufiz

Build from Source

git clone https://github.com/Mufi-Lang/MufiZ.git
cd MufiZ
zig build

Build Options

MufiZ supports various build features that can be enabled or disabled:

  • -Denable_net - Enables the network module
  • -Denable_fs - Enables the filesystem module
  • -Dsandbox - Enables sandbox mode (REPL only)

Language Syntax

Basic Usage

// Run a script
mufiz --run script.mufi

// Start interactive REPL
mufiz --repl

// Link additional scripts
mufiz --run main.mufi --link utils.mufi

// Show help
mufiz --help

Data Structures

Float Vectors

var vector = {1, 2, 3, 4, 5};
var coords = {10.5, 20.3, 15.8};

Hash Tables

var dict = #{"key": "value", "name": "John"};
var config = #{"debug": true, "port": 8080};

Variables and Constants

// Variables (mutable)
var x = 10;
var name = "MufiZ";

// Constants (immutable)
const PI = 3.14159;
const VERSION = "0.10.0";

Control Flow

Conditionals

if (x > 0) {
    print("Positive");
} else if (x < 0) {
    print("Negative");
} else {
    print("Zero");
}

Switch Statements

switch(value) {
    case 1 => { print("One"); },
    case 2 => { print("Two"); },
    _ => { print("Other"); }
}

Loops

For Loops

for (var i = 0; i < 10; i = i + 1) {
    print(i);
}

Foreach Loops

// Range iteration
foreach (i in 1..10) {
    print(i);
}

// Collection iteration
var list = {1, 2, 3, 4, 5};
foreach (item in list) {
    print(item);
}

While Loops

var i = 0;
while (i < 10) {
    print(i);
    i = i + 1;
}

Functions

fun add(a, b) {
    return a + b;
}

fun greet(name) {
    return format("Hello, {}!", name);
}

String Formatting

// Using format function
var name = "World";
var greeting = format("Hello, {}!", name);

// F-string style (alias for format)
var message = f("The answer is {}", 42);

Standard Library Functions

MufiZ provides a comprehensive standard library organized into modules:

Core Functions

Core Function Examples

// Type checking and conversion
var data = input();                // Read user input
var dataType = what_is(data);      // Check type: "string"

// Convert between types
var numStr = "42";
var number = int(numStr);          // 42
var decimal = double("3.14");      // 3.14
var text = str(number);            // "42"

// Input validation
print("Enter your age:");
var ageInput = input();
if (what_is(int(ageInput)) == "number") {
    var age = int(ageInput);
    print(format("You are {} years old", age));
}

Input/Output Functions

  • input() - Reads input from stdin
  • print(value) - Prints value to stdout

Type Conversion Functions

  • int(value) - Converts to integer
  • double(value) - Converts to double
  • str(value) - Converts to string

Type Inspection Functions

  • what_is(value) - Returns type as string

Math Functions

Math Function Examples

// Basic mathematical operations
var distance = abs(-5.5);          // 5.5
var squared = pow(4, 2);           // 16
var root = sqrt(16);               // 4.0

// Trigonometry (angles in radians)
var piVal = pi();                  // 3.141592653589793
var sineVal = sin(piVal / 2);      // 1.0
var cosineVal = cos(0);            // 1.0

// Logarithms
var naturalLog = ln(2.718);        // ≈ 1.0
var log2Val = log2(8);             // 3.0

// Random numbers
var random = rand();               // 0.0 to 1.0
var gaussian = randn();            // Normal distribution

// Complex numbers
var c1 = complex(3, 4);            // 3 + 4i
var angle = phase(c1);             // Phase angle

Basic Functions

  • abs(number) - Absolute value
  • pow(base, exp) - Power function
  • sqrt(number) - Square root
  • ceil(number) - Ceiling function
  • floor(number) - Floor function
  • round(number) - Round to nearest integer
  • max(a, b) - Maximum of two numbers
  • min(a, b) - Minimum of two numbers

Trigonometric Functions

  • sin(number) - Sine function
  • cos(number) - Cosine function
  • tan(number) - Tangent function
  • asin(number) - Arcsine function
  • acos(number) - Arccosine function
  • atan(number) - Arctangent function

Logarithmic Functions

  • ln(number) - Natural logarithm
  • log2(number) - Base-2 logarithm
  • log10(number) - Base-10 logarithm

Random & Constants

  • pi() - Pi constant
  • rand() - Random float [0,1)
  • randn() - Random normal distribution

Complex Numbers

  • complex(real, imag) - Creates complex number
  • phase(complex) - Phase of complex number

Collections Functions

Collections Examples

// Create data structures
var myList = linked_list();
var userDB = hash_table();
var measurements = fvec(100);

// List operations
push(myList, "item1");
push(myList, "item2");
var item = pop(myList);

// Hash table operations
put(userDB, "name", "Alice");
var name = get(userDB, "name");

// Vector operations
var vec1 = {1, 2, 3};
var vec2 = {4, 5, 6};
var dot_product = dot(vec1, vec2);    // 32
var magnitude = norm(vec1);           // √14

// Statistical operations
var scores = {85, 92, 78, 96, 88};
var average = mean(scores);           // 87.8
var total = sum(scores);              // 439

Data Structure Creation

  • linked_list() - Creates new linked list
  • hash_table() - Creates new hash table
  • fvec(capacity) - Creates new float vector

List Operations

  • push(list, value) - Adds element to end of list
  • pop(list) - Removes last element
  • push_front(list, value) - Adds element to front
  • pop_front(list) - Removes first element
  • insert(list, index, value) - Inserts element at index
  • remove(collection, key) - Removes element

Access & Query

  • len(list) - Gets length of list
  • get(list, index) - Gets element at index
  • nth(list, index) - Gets nth element
  • contains(list, value) - Checks if list contains value
  • is_empty(list) - Checks if list is empty

Hash Table Operations

  • put(hash_table, key, value) - Puts element into hash table
  • pairs(hash_table) - Gets key-value pairs

Vector Operations

  • linspace(start, end, count) - Creates evenly spaced values
  • dot(vector1, vector2) - Dot product
  • cross(vector1, vector2) - Cross product (3D)
  • norm(vector) - Euclidean norm
  • proj(vector1, vector2) - Vector projection
  • angle(vector1, vector2) - Angle between vectors

Statistical Functions

  • sum(vector) - Sum of all elements
  • mean(vector) - Mean of all elements
  • std(vector) - Standard deviation
  • vari(vector) - Variance of elements
  • maxl(vector) - Maximum element
  • minl(vector) - Minimum element

Filesystem Functions

Filesystem Examples

// File operations
create_file("data.txt");
write_file("data.txt", "Hello, MufiZ!");
var content = read_file("data.txt");
delete_file("data.txt");

// Directory operations
create_dir("my_project");
create_dir("my_project/src");

// Organize project files
create_file("my_project/README.md");
write_file("my_project/README.md", "# My Project");

create_file("my_project/src/main.mufi");
write_file("my_project/src/main.mufi", 'print("Hello!");');

// Clean up
delete_file("my_project/README.md");
delete_file("my_project/src/main.mufi");
delete_dir("my_project/src");
delete_dir("my_project");

File Operations

  • create_file(path) - Creates new file
  • read_file(path) - Reads file content
  • write_file(path, content) - Writes to file
  • delete_file(path) - Deletes file

Directory Operations

  • create_dir(path) - Creates directory
  • delete_dir(path) - Deletes directory

Note: Filesystem functions require the -Denable_fs build flag when compiling MufiZ.

Network Functions

Network Examples

// HTTP requests
var response = http_get("https://api.github.com/users/octocat");

// POST with JSON data
set_content_type("application/json");
var userData = '{"name": "Alice", "email": "[email protected]"}';
var postResponse = http_post("https://httpbin.org/post", userData);

// Authentication
set_auth("Bearer your-api-token");
var authResponse = http_get("https://api.example.com/protected");

// URL utilities
var encoded = url_encode("Hello World!");  // "Hello%20World!"
var decoded = url_decode(encoded);         // "Hello World!"
var urlParts = parse_url("https://api.example.com/users?id=123");

// Open URL in browser
open_url("https://github.com/Mufi-Lang/MufiZ");

HTTP Requests

  • http_get(url) - Performs HTTP GET request
  • http_post(url, data) - Performs HTTP POST request
  • http_put(url, data) - Performs HTTP PUT request
  • http_delete(url) - Performs HTTP DELETE request

Configuration

  • set_content_type(type) - Sets content type for requests
  • set_auth(token) - Sets authorization token

URL Utilities

  • parse_url(url) - Parses URL into components
  • url_encode(string) - URL encodes a string
  • url_decode(string) - Decodes URL encoded string
  • open_url(url) - Opens URL in default browser

Note: Network functions require the -Denable_net build flag when compiling MufiZ.

Time Functions

Time Examples

// Get current timestamps
var currentTime = now();          // Unix timestamp in seconds
var milliTime = now_ms();         // Milliseconds since Unix epoch
var nanoTime = now_ns();          // Nanoseconds since Unix epoch

// Measure execution time
var startTime = now_ms();
sleep(1);  // Wait 1 second
var endTime = now_ms();
var duration = endTime - startTime;  // ~1000 ms

// Timeout checking
var operationStart = now();
var timeoutLimit = 30;  // 30 seconds
while ((now() - operationStart) < timeoutLimit) {
    // Do work...
    print("Working...");
    sleep(1);
}

// Rate limiting
var lastRequest = 0;
var minInterval = 1;  // 1 second between requests
if ((now() - lastRequest) >= minInterval) {
    // Make request
    lastRequest = now();
}

Timestamp Functions

  • now() - Current timestamp in seconds
  • now_ns() - Current timestamp in nanoseconds
  • now_ms() - Current timestamp in milliseconds

Utility Functions

Utility Examples

// Program control
exit(0);                    // Exit with success code
sleep(2);                   // Wait 2 seconds
panic("Critical error!");   // Terminate with error message

// Testing and debugging
assert(2 + 2 == 4);         // Test condition
var result = someFunction();
assert(result != null);     // Ensure valid result

// String formatting
var name = "Alice";
var age = 25;
var greeting = format("Hello, {}! Age: {}", name, age);
var shortForm = f("Hi, {}!", name);  // F-string syntax

// Error handling patterns
if (errorCondition) {
    print("Error occurred");
    exit(1);
} else {
    print("Success!");
    exit(0);
}

Program Control

  • exit(code?) - Exits program with optional code
  • sleep(seconds) - Sleeps for given seconds
  • panic(message?) - Panics with optional message

Testing & Debugging

  • assert(condition) - Asserts condition is true

String Formatting

  • format(template, values...) - Formats string with placeholders
  • f(template, values...) - Alias for format (f-string syntax)

Matrix Functions

Matrix Examples

// Create matrices
var I3 = eye(3);                    // 3x3 identity matrix
var onesMatrix = ones(2, 3);        // 2x3 matrix of ones
var zerosMatrix = zeros(3, 2);      // 3x2 matrix of zeros
var randMatrix = rand(2, 2);        // Random matrix

// Matrix operations
var A = [[1, 2, 3], [4, 5, 6]];
var AT = transpose(A);              // Transpose
var matSize = size(A);              // Get dimensions
var traceA = trace(A);              // Diagonal sum

// Element access
var element = matrix_get(A, 0, 1);  // Get A[0,1]
matrix_set(A, 0, 1, 99);           // Set A[0,1] = 99

// Matrix concatenation
var left = [[1, 2], [3, 4]];
var right = [[5, 6], [7, 8]];
var combined = horzcat(left, right); // Horizontal concat

Matrix Creation

  • eye(n) or eye(m, n) - Creates identity matrix
  • ones(m, n) - Creates matrix of ones
  • zeros(m, n) - Creates matrix of zeros
  • rand(m, n) - Creates random matrix
  • randn(m, n) - Creates random normal matrix
  • matrix(data, rows, cols) - Create matrix from data

Matrix Operations

  • transpose(A) - Matrix transpose
  • det(A) - Matrix determinant
  • inv(A) - Matrix inverse
  • trace(A) - Matrix trace
  • norm(A) - Frobenius norm
  • rank(A) - Matrix rank
  • rref(A) - Reduced row echelon form

Matrix Manipulation

  • size(A) - Matrix dimensions
  • reshape(A, m, n) - Reshape matrix
  • horzcat(A, B) - Horizontal concatenation
  • vertcat(A, B) - Vertical concatenation
  • matrix_get(A, row, col) - Get matrix element
  • matrix_set(A, row, col, value) - Set matrix element
  • flatten(A) - Flatten matrix to vector

Release History

Version Codename Status Key Features
0.10.0 Echo Latest Enhanced REPL, improved input handling, terminal optimizations
0.9.0 Kova Released Performance improvements, bug fixes
0.8.0 Ruby Released Matrix operations, linear algebra support
0.7.0 Jade Released SIMD optimizations, hash table improvements
0.6.0 Mars Released Memory optimizations, arena allocators