app [main] { pf: platform "https://github.com/roc-lang/basic-cli/releases/download/0.16.0/O00IPk-Krg_diNS2dVWlI0ZQP794Vctxzv0ha96mK0E.tar.br" } import pf.Stdout # Functions to work with in the reduce function add = \a, b -> a + b mult = \a, b -> a * b reduce : (List (Num a)), U64, Num a, (Num a, Num a -> Num a) -> Num a reduce = \nums, counter, neutral, func -> if counter == (List.len nums) then neutral else currentValue = listI nums counter (func currentValue (reduce nums (counter + 1) neutral func)) sum : (List (Num a)), U64 -> Num a sum = \nums, counter -> if counter == (List.len nums) then 0 else currentValue = listI nums counter ((sum nums (counter + 1)) + currentValue) # Gets the value in a list at a given index # Returns 0 if the index is out of bounds listI: (List (Num a)), U64 -> Num a listI = \list, i -> res = List.get list i when res is Ok value -> value Err OutOfBounds -> 0 main = firstHun = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100] firstTen = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sumFirstHundred = sum firstHun 0 sumFirstHundredReduce = reduce firstHun 0 0 add productFirstTenReduce = reduce firstTen 0 1 mult Stdout.line! "Sum first 100 rational numbers = $(Num.toStr sumFirstHundred)" Stdout.line! "Sum first 100 rational numbers using reduce = $(Num.toStr sumFirstHundredReduce)" Stdout.line! "Product first 10 rational numbers = $(Num.toStr productFirstTenReduce)"