Amethyst for F# developers
The Amethyst compiler is written in F#. So we know exactly what we’re asking you to give up, and we’re asking anyway.
Both languages run on .NET and can call each other, and both have type inference and
blocks of code you can pass around. Beyond that, they come from opposite ends of the
family: F# descends from ML, and Amethyst descends from Ruby. Expect more end, fewer
pipes, and a compiler that will happily let you reassign a variable.
Hello, world
Section titled “Hello, world”printfn "Hello, world!"def main: Void puts "Hello, world!"endFunctions are methods
Section titled “Functions are methods”Functions become def methods. Arguments go in parentheses with commas, and nothing is
curried.
let add x y = x + ylet add5 = add 5
let greet (name: string) = $"Hello, {name}!"def add(x: Int, y: Int): Int x + yend
add5 = ->(y: Int) { add(5, y) }
def greet(name: String): String "Hello, #{name}!"endPartial application is spelled ->.
Type inference, but less of it
Section titled “Type inference, but less of it”F# infers types across whole functions. Amethyst infers less: local variables, generic
arguments from constructors, and the return types of private methods. Public methods
spell out their return type. Leave it out and the method returns nil, whatever its
last expression is. See Return Type Rules by Visibility.
You can still leave out a parameter’s type. The compiler then works out what the argument must provide from how the method uses it, and checks each call site against that. See Structural Typing.
| F# | Amethyst |
|---|---|
int, int64, float |
Int, Long, Float |
'T |
T, declared in brackets: def identity[T](x: T): T |
ResizeArray<'T>, Dictionary<'K, 'V> |
Array[T], Hash[K, V] |
unit |
Void or Nil, both compile to void |
Mutable by default
Section titled “Mutable by default”F# makes you ask for let mutable. In Amethyst, assignment declares a variable, and
assigning again changes it. Names in ALL_CAPS are constants. Everything else is
mutable, so the compiler won’t stop you reassigning things. Your code review might.
let name = "Ada"let mutable count = 0count <- count + 1name = "Ada"count = 0count += 1[1; 2; 3] is now [1, 2, 3], and it’s a mutable List<T>, not an immutable
linked list.
Pipelines become method chains
Section titled “Pipelines become method chains”There’s no |>. Collection functions are methods, from
Enumerable[T], so a pipeline becomes a chain.
let names = users |> List.filter (fun u -> u.IsActive) |> List.sortBy (fun u -> u.Name) |> List.map (fun u -> u.Name)names = users.select(&:active?).sort_by(&:name).map(&:name)| F# | Amethyst |
|---|---|
List.filter |
select |
List.map |
map |
List.collect |
flat_map |
List.fold |
reduce |
List.exists / List.forall |
any? / all? |
List.tryHead |
first (returns T?) |
select filters, and map projects. The SQL part of your brain will object.
Option becomes T?
Section titled “Option becomes T?”There’s no Option. A value that might be missing has a nullable type, T?, and a
nil check narrows it to T. &. takes the place of Option.bind and Option.map.
let city = findUser id |> Option.bind (fun u -> u.Address) |> Option.map (fun a -> a.City)city = find_user(id)&.address&.cityThere’s no Result either. Errors are .NET exceptions, raised with raise and caught
with rescue. See Error Handling.
Discriminated unions
Section titled “Discriminated unions”This is the one you’ll miss. Amethyst’s complex enums look like unions, but they’re Java-style enums: each case is a single instance, and every case has the same fields. For cases that carry different data, use a base class with a subclass per case, then match on the type.
type Shape = | Circle of radius: float | Rectangle of width: float * height: float
let area shape = match shape with | Circle r -> Math.PI * r * r | Rectangle (w, h) -> w * hclass Shapeend
class Circle < Shape getter radius: Float # ...end
class Rectangle < Shape getter width: Float getter height: Float # ...end
def area(shape: Shape): Float case shape when Circle then Math::PI * shape.radius ** 2 when Rectangle then shape.width * shape.height else 0.0 endendMatching on a type narrows the value inside the branch, but when can’t destructure
it, and the compiler doesn’t check that you’ve covered every case. That’s what the
else is for. Pattern matching is planned for a
future revision. Until then, F# wins this one outright.
Computation expressions
Section titled “Computation expressions”async and task computation expressions become async methods. You write the
unwrapped return type, and the compiler returns a Task.
let fetch (url: string) = task { let! response = http.GetAsync(url) return! response.Content.ReadAsStringAsync()}async def fetch(url: String): String response = await http.get_async(url) await response.content.read_as_string_asyncendFor other builders, Amethyst has receiver blocks. They’re less general than computation expressions, but they’re how you write a DSL.
Everything else
Section titled “Everything else”| F# | Amethyst |
|---|---|
open System.Text |
use System::Text |
namespace MyApp.Models |
namespace MyApp::Models |
module of functions |
Top-level methods, or a mixin with extend self |
interface |
protocol, adopted with implements |
[<Serializable>] |
@[Serializable] |
fun x -> x * 2 |
{ |x| x * 2 } or ->(x: Int) { x * 2 } |
(1, "a"), fst pair |
(1, "a"), pair.0 |
failwith "oops" |
raise "oops" |
try … with |
begin … rescue … end |
use reader = new StreamReader(path) |
StreamReader.new(path).use do |reader| … end, on anything Disposable |
printfn "%d" count |
puts count, or "#{count}" for formatting |
| Significant whitespace | end. Indent however you like; the compiler isn’t watching |
| Units of measure | None. Your metres and your feet will have to trust each other |
| Type providers | None |
.fsproj |
project.am |