/ 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:

[<EntryPoint>]
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 Netkachov is a Senior Software Developer, currently working in Central London on new generation of energy trading solutions for brokers, traders and exchanges.

Read More

Why not to chat about this post? Join Telegram group Alex@Net or message on Twitter to alex_at_net. Alternatively, use the comments form below.