Last active
August 29, 2015 14:02
-
-
Save robotlolita/4e91d3a245401ed63e11 to your computer and use it in GitHub Desktop.
Solving the expression problem in Harmonia (with structural typing through row-polymorphism and multi-methods)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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