Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Solving the expression problem in Harmonia (with structural typing through row-polymorphism and multi-methods)
module Expression using: Platform where
open Platform Math expose [sqrt, +, -, *, /, π]
open Platform IO expose [print]
type Circle = { radius :: Double }
type Square = { side :: Double }
let { _ | side: s } area = s * s -- inferred type: { a | side :: Double } -> Double
let { _ | radius: r } area = π * r * r -- inferred type: { a | radius :: Double } -> Double
-- Adding a new Triangle type
type Triangle = { adjacent :: Double, opposite :: Double, hypotenuse :: Double }
let { _ | adjacent: a, opposite: b, hypotenuse: h } area = p * (p - a) * (p - b) * (p - c) |> sqrt
where
p = (a + b + c) / 2
-- Adding a new `perimeter` operation to all types
let { _ | side: s } perimeter = 4 * s
let { _ | radius: r } perimeter = 2 * π * r
let { _ | adjacent: a, opposite: b, hypotenuse: h } perimeter = a + b + h
-- Using it
let (a, b, c) triangle = { adjacent: a, opposite: b, hypotenuse: c }
let main = do
{ side: 10 } perimeter print. -- 40
{ side: 5 } area print. -- 25
{ radius: 3 } perimeter print. -- 18.84955592153876
{ radius: 5 } area print. -- 28.274333882308138
(2, 3, 4) triangle area print. -- 8.4375
(2, 3, 4) triangle perimeter print. -- 9
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment