Task

Remove a specific line or a number of lines from a file.

This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).

For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2

Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed.

An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.




open System
open System.IO
 
let cutOut (arr : 'a[]) from n =  // confine syntax highlighting confusion'
    let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
    ((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
 
[<EntryPoint>]
let main argv =
    let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
    let lines = File.ReadAllLines(argv.[0])
    let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
    if tooShort then Console.Error.WriteLine "Not enough lines"
    File.WriteAllLines(argv.[0], sliced)
    0