/ F#

HR F#: Reverse a List

The problem Reverse a List encourages to learn List.rev.

You are given a list of elements. Reverse the list without using the reverse function.

The simplest implementation is not very efficient one but it works good enough to pass the tests:

let rev (lst : List<'T>) =
  let length = List.length lst
  seq { for i in (length-1) .. -1 .. 0 do yield lst.[i] }
  |> Seq.toList

The main method:

let main argv = 
    readItemsFromInput ()
    |> Seq.toList
    |> rev
    |> Seq.iter (fun v -> printfn "%A" v)
    0 // return an integer exit code

Complexity of the solution is O(N²) because getting list item is O(N) and it should be done for very item of the list. The alternative can be using structure with O(1). You can try to do it as an exercise.

Alex Netkachov

Alex Netkachov

Alex likes functional programming, algorithms and code reviews. Apart from programming, his favourites are walking with his family in the parks and national trails and reading books.

Read More

Why not to stay updated if the subject is interesting? Join Telegram channel Alex@Net or follow alex_at_net on Twitter. Or just, use the comments form below.