Hi, I’m trying to do a function that returns the minimum from a list but it doesn’t let me use the sort function so that I can take the first element after I mapp the list according to the criteria, does anyone has a suggestion of how can I fix it or how can I do this function?
{-| Description for minimumBy
minimumBy .x [ { x = 1, y = 2 } ] --> Just {x = 1, y = 2}
minimumBy .x [] --> Nothing
minimumBy (modBy 10) [ 16, 23, 14, 5 ] --> Just 23
-}
minimumBy : (a → comparable) → List a → Maybe a
minimumBy cond l =
let
mapped = List.map cond l
sorted = mapped.sort
in
case l of
→ Nothing
x::xs → Just (sorted.take 1)
If you want to write it by first sorting a mapped list, you are on the right track, but your line
sorted = mapped.sort
will not work because there aren’t any methods in Elm, it’s all functions, qualified with their module prefix or not, depending on how you import the module.
In your case, you’d have to write something like:
sorted = List.sort mapped
Same for sorted.take which does not exist. But even then, this would not correspond to the specification you wrote in the description, because you’d be returning the value from the mapped list instead of the original one.
So if you want to do it and return the value from the original list, you could instead use List.sortBy.
minimumBy compareFn list =
List.head (List.sortBy compareFn list)
This implementation is pretty simple, but quite expensive as you are sorting the full array instead of just looking for its minimum. For now this is probably enough, but when you get more experience with elm, I suggest you look into the implementation in the list-extra package.