/ F#

HR F#: Updating List

The problem Updating List requires learning how to generate one list from another.

Update the values of a list with their absolute values.

In many other programming languages the common approach is to update the array items: a[i] = abs(a[i]);, e.g. modify the shared state. The functional way change the list implies using immutable data structures so instead of modifying the list let's generate the new one with negative elements inverted:

// this function returns new list created by inverting
// negative items in the given list arr
let f arr = arr |> List.map (fun v -> if v < 0 then -v else v)

//----------------DON'T MODIFY---------------
let input = 
    stdin.ReadToEnd().Split '\n' 
    |> Array.map(fun x -> int(x)) 
    |> Array.toList
let print_out (data:int list) = List.iter (fun x -> printfn "%A" x) data

print_out (f(input))
Alex Netkachov

Alex Netkachov

Alex likes functional programming and algorithms. Apart from programming, his favourites are walking with his family in the parks and national trails and reading about universe and history.

Read More