Skip to content

Instantly share code, notes, and snippets.

@iliyan-trifonov
Created September 2, 2016 17:25
Show Gist options
  • Save iliyan-trifonov/6113bbc476a1e9f4d9b653ae5d9f3545 to your computer and use it in GitHub Desktop.
Save iliyan-trifonov/6113bbc476a1e9f4d9b653ae5d9f3545 to your computer and use it in GitHub Desktop.
Convert a for loop to get the min and max values from a list to Elm code
-- original JS code
-- var list = [ 3, 42, 73, 2 ];
-- var min = list[0], max = list[0];
-- for (var i = 0; i < list.length; i++) {
-- min = Math.min(min, list[i]);
-- max = Math.max(max, list[i]);
--}
-- we will use Html.text to show the result
import Html exposing (text)
-- let's call the function `findMinMax`
-- it takes a list of integers
-- and the initial min and max values(taken from the first item in the list) as a tuple (min, max)
-- and returns a tuple: (min, max)
findMinMax : List Int -> (Int, Int) -> (Int, Int)
-- TODO: replace `tpl` with `(min, max)` here?
findMinMax list tpl =
case list of
-- stop the recursion on empty list
[] ->
tpl
-- check the head value, continue with the tail
x::xs ->
let
(min, max) = tpl
min2 = intFromMaybe (List.minimum [x, min])
max2 = intFromMaybe (List.maximum [x, max])
in
findMinMax xs (min2, max2)
-- get an Int from Maybe value, crash on unexpected Nothing value
intFromMaybe : Maybe Int -> Int
intFromMaybe mnum =
case mnum of
Just x ->
x
Nothing ->
Debug.crash "fromMaybe: not a number!"
main =
-- define the list and the initial min and max values(using the first element from the list) and call the function
let
-- define the list
list : List Int
list = [3, 42, 73, 2]
-- define the initial min value
initMin : Int
initMin = intFromMaybe (List.head list)
-- define the initial max value
initMax : Int
initMax = initMin
in
text ( toString ( findMinMax list (initMin, initMax) ) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment