---
source: crates/wolf_parser/tests/parser.rs
expression: result.dump
---
file
doc! " Shapes: an interface used as a value type (`List<Shape>`), sorting with a closure, and"
doc! " `Comparable` implemented by a user type."
module main
(section imports (import std.list))
section types
(struct Rect (field w Float) (field h Float))
(struct Square (field side Float))
(struct Triangle (field base Float) (field height Float))
section interfaces
(interface Shape (sig area (params self) (-> Float)) (sig name (params self) (-> String)))
section impl
impl
Rect
(for Shape)
(fn area (params self) (-> Float) (block (* (. self w) (. self h))))
(fn name (params self) (-> String) (block "rectangle"))
impl
Rect
(for Comparable)
fn
compare
(params self (other Self))
(-> Ordering)
(block (call compare_floats (call (. self area)) (call (. other area))))
impl
Square
(for Shape)
(fn area (params self) (-> Float) (block (* (. self side) (. self side))))
(fn name (params self) (-> String) (block "square"))
impl
Triangle
(for Shape)
(fn area (params self) (-> Float) (block (/ (* (. self base) (. self height)) 2.0)))
(fn name (params self) (-> String) (block "triangle"))
section main
fn
main
()
block
var
shapes
(List Shape)
list
(struct Rect (w: 3.0) (h: 4.0))
(struct Square (side: 2.0))
(struct Triangle (base: 6.0) (height: 5.0))
call
(. list sort_by)
(mut shapes)
(closure (params a b) (call compare_floats (call (. a area)) (call (. b area))))
for
shape
shapes
block
call
print
(+ (+ (call (. shape name)) ": ") (call (. (call (. shape area)) to_string)))
(call print (+ "total: " (call (. (call total_area shapes) to_string))))
let
rects
list
(struct Rect (w: 1.0) (h: 1.0))
(struct Rect (w: 2.0) (h: 3.0))
(struct Rect (w: 0.5) (h: 2.0))
match
(call (. list max) rects)
=>
(Some r)
call
print
+
(+ (+ "largest rectangle: " (call (. (. r w) to_string))) " x ")
(call (. (. r h) to_string))
(=> None (call print "no rectangles"))
section functions
fn
doc " `Float` is not `Comparable` (NaN), so floats are compared by hand."
compare_floats
(params (a Float) (b Float))
(-> Ordering)
block
if
(< a b)
(block (. Ordering Less))
(else (if (> a b) (block (. Ordering Greater)) (else (block (. Ordering Equal)))))
fn
total_area
(params (shapes (List Shape)))
(-> Float)
(block (var sum 0.0) (for shape shapes (block (+= sum (call (. shape area))))) sum)