module Station.Collections from Myceta.Collections.Map import * as Map from Myceta.Collections.Set import * as Set dimension Length quantity Rainfall = Length unit m: Length unit mm: Rainfall fn latest(xs: array>) -> optional> = if array.length(xs) == 0 then none else some(xs[array.length(xs) - 1]) fn orElse(value: optional>, fallback: f64) -> f64 = match value { some(v) -> v none -> fallback } fn surveyNote(found: optional>) -> text = match found { some(_) -> "surveyed" none -> "not surveyed" } fn checked(level: f64) -> Result, text> = if level < 0.0 then #Result.Err("negative rainfall") else #Result.Ok(level) fn checkedSum(a: f64, b: f64) -> Result, text> = match checked(a) { Err(reason) -> #Result.Err(reason) Ok(first) -> match checked(b) { Err(reason) -> #Result.Err(reason) Ok(second) -> #Result.Ok(first + second) } } fn report(result: Result, text>) -> text = match result { Ok(_) -> "accepted" Err(reason) -> "rejected: " ++ reason } node Rain = [4.0, 12.5, 31.0] node WithToday = array.append(Rain, 0.5) node DayCount = array.length(WithToday) node FirstDay = Rain[0] node Typical = 10.0 node Latest = latest(Rain) node LatestOrTypical = orElse(Latest, Typical) node NoReadings = latest(([] as array>)) node Carried = NoReadings ?? Typical node Guarded = let some(v) = Latest else Typical node Wind = vector[3.0, 4.0] node WindCount = vector.length(Wind) node Grid = matrix[[1.0, 2.0], [3.0, 4.0]] node GridRows = matrix.rows(Grid) node Flipped = matrix.transpose(Grid) node Elevation = { let m0 = Map.empty>(); let m1 = Map.insert(m0, "Harbor", 3.0); Map.insert(m1, "Ridge", 410.0) } node RidgeNote = surveyNote(Map.get(Elevation, "Ridge")) node ValleyNote = surveyNote(Map.get(Elevation, "Valley")) node KnowsValley = Map.containsKey(Elevation, "Valley") node Coastal = { let s0 = Set.empty(); Set.insert(s0, "Harbor") } node Reporting = { let s0 = Set.empty(); let s1 = Set.insert(s0, "Harbor"); Set.insert(s1, "Ridge") } node CoastalReporting = Set.intersection(Coastal, Reporting) node HarborReports = Set.contains(CoastalReporting, "Harbor") node GoodSum = report(checkedSum(4.0, 12.5)) node BadSum = report(checkedSum(4.0, -1.0)) test CollectionsBehave { expect DayCount : OK with value = 4 expect FirstDay : OK with value = 4.0 within 0.001 expect LatestOrTypical : OK with value = 31.0 within 0.001 expect Carried : OK with value = 10.0 within 0.001 expect Guarded : OK with value = 31.0 within 0.001 expect WindCount : OK with value = 2 expect GridRows : OK with value = 2 expect RidgeNote : OK with value = "surveyed" expect ValleyNote : OK with value = "not surveyed" expect KnowsValley : OK with value = false expect HarborReports : OK with value = true expect GoodSum : OK with value = "accepted" expect BadSum : OK with value = "rejected: negative rainfall" }