From c1d3cc12b920f60d06265b645daa3ff0010a8402 Mon Sep 17 00:00:00 2001 From: Connor Schembor Date: Thu, 5 Nov 2020 21:28:32 -0500 Subject: Add product function to int and float modules --- src/gleam/float.gleam | 21 +++++++++++++++++++++ src/gleam/int.gleam | 21 +++++++++++++++++++++ 2 files changed, 42 insertions(+) (limited to 'src') diff --git a/src/gleam/float.gleam b/src/gleam/float.gleam index 3d611b5..8018c95 100644 --- a/src/gleam/float.gleam +++ b/src/gleam/float.gleam @@ -190,3 +190,24 @@ fn do_sum(numbers: List(Float), initial: Float) -> Float { [x, ..rest] -> do_sum(rest, x +. initial) } } + +/// Multiplies a list of Floats and returns the product. +/// +/// ## Example +/// +/// > product([2.5, 3.2, 4.2]) +/// 33.6 +/// +pub fn product(numbers: List(Float)) -> Float { + case numbers { + [] -> 0. + _ -> do_product(numbers, 1.) + } +} + +fn do_product(numbers: List(Float), initial: Float) -> Float { + case numbers { + [] -> initial + [x, ..rest] -> do_product(rest, x *. initial) + } +} diff --git a/src/gleam/int.gleam b/src/gleam/int.gleam index 0bbd63d..002a155 100644 --- a/src/gleam/int.gleam +++ b/src/gleam/int.gleam @@ -167,3 +167,24 @@ fn do_sum(numbers: List(Int), initial: Int) -> Int { [x, ..rest] -> do_sum(rest, x + initial) } } + +/// Multiplies a list of Ints and returns the product. +/// +/// ## Example +/// +/// > product([2, 3, 4]) +/// 24 +/// +pub fn product(numbers: List(Int)) -> Int { + case numbers { + [] -> 0 + _ -> do_product(numbers, 1) + } +} + +fn do_product(numbers: List(Int), initial: Int) -> Int { + case numbers { + [] -> initial + [x, ..rest] -> do_product(rest, x * initial) + } +} -- cgit v1.2.3