Damien Gonot
Home Blog Notes About

Futhark

Homepage / Notes / Computer Science / Programming Languages / Niche Languages / Futhark

Futhark is a small programming language designed to be compiled to efficient parallel code. It is a statically typed, data-parallel, and purely functional array language in the ML family, and comes with a heavily optimising ahead-of-time compiler that presently generates either GPU code via CUDA and OpenCL, or multi-threaded CPU code. https://futhark-lang.org/

Language Features

Basic

Compile (CPU) futhark code

futhark c main.fut

Run

./main

Run with arguments:

echo 9 | ./main

Compile (GPU - OpenCL) futhark code

futhark opencl main.fut

REPL

futhark repl

Primitives

https://futhark-lang.org/examples/values.html

Integers

def an_int : i32 = 9

Floats

def a_float : f64 = 9.0

Booleans

def a_boolean = true

Arrays

https://futhark-lang.org/examples/arrays.html

def arr = [1,2,3]

arr
[1i32, 2i32, 3i32]

Arrays of arrays have to be of the same size:

def marr = [[1,2,3], [4,5,6]]

marr
[[1i32, 2i32, 3i32], [4i32, 5i32, 6i32]]

This is illegal:

def marr = [[1,2,3], [4,5]]
Dimensions "3" and "2" do not match.

Index

Arrays are indexed from zero:

arr[0]
1i32

Slice

Arrays can be sliced:

arr[1:]
[2i32, 3i32]

Reverse

Strides are supported

arr[::-1]
[3i32, 2i32, 1i32]

Iota

iota 5
[0i64, 1i64, 2i64, 3i64, 4i64]

Range

Three dots, not two

1...5
[1i32, 2i32, 3i32, 4i32, 5i32]

Replicate

replicate 3 9
[9i32, 9i32, 9i32]

Map

map (+1) [1, 2, 3]
[2i32, 3i32, 4i32]

Map2

Reduce

reduce (+) 0 [1, 2, 3]
6i32

Scan

scan (+) 0 [1, 2, 3, 4]
[1i32, 3i32, 6i32, 10i32]

Tuples

def a_tuple = (1, true)

a_tuple
(1i32, true)
a_tuple.0
1i32

Records

def a_record = {foo = 1, bar = true}

a_record
{bar = true, foo = 1i32}
a_record.foo
1i32

Functions

https://futhark-lang.org/examples/functions.html

With type inference:

def plus1 x =
  x + 1

With declared types:

def plus1 (x: i32) : i32 =
  x + 1
def sum a = reduce (+) 0 a
sum [1, 2, 3]
6i32

Functions as infix operator

def plus = (+)
2 `plus` 2
4i32

Pipe operator

[1,2,3,4] |> scan (+) 0 |> reduce (+) 0
20i32

Sequential Loops

loop x = 1 for i < 5 do
  x * (i + 1)

Literate Futhark

https://futhark-lang.org/examples/literate-basics.html

futhark literate {filename}

Convert a .fut file to a .md file. For specially formatted comments (directives), results are appended.

Resources

Parallel Programming in Futhark

https://futhark-book.readthedocs.io/en/latest/

Futhark User's Guide

https://futhark.readthedocs.io/en/stable/