Search code examples
f#system.io.file

Using System.IO.File.ReadAllText to reverse a .txt-file


So, I'm trying to write a code that takes a list of .txt-files and the output I'm hoping for is that the console spits out the contents of the files, appended and in reverse. I know you can use System.IO.File.ReadAllText in order to spit out the text of a file, but is there a good way to spit the contents of a file out, but reversed?

I have a readFile command that looks like this

module readNWrite
open System.IO

let readFile (filename : string) : string option =
    if File.Exists filename then
       Some (File.ReadAllText filename)
    else None

And so far, my code for printing out a list of files in reverse looks like this

let tac (filenames : string list) : string option =
    let rec help (helpLst : string list) (helpStr : string) :string option =
        match helpLst.rev with
            | [] -> Some (helpStr)
            | head :: tail -> match readFile (head) with
                                | None -> None
                                | Some(x) -> help (tail) (helpStr + x)
    help filenames ""

Which just spits out the .txt-files, appended.


Solution

  • If I was trying to do this for real, rather than just for educational purposes, I would probably write something like this:

    open System
    open System.IO
    
    for file in files do
      let contents = File.ReadAllText(file).ToCharArray()
      let reversed = String(Array.rev contents)
      printfn "%s" reversed
    
    • The code does not use recursion. If you are learning recursion, reversing a list is a fun problem. In practice, you can do most things using built-in functions.
    • It has an imperative for loop. But the whole point of the program is imperative - printing - so there is no reason not to do this.
    • You could use a more elegant pipeline with Seq.rev (which works directly on strings), but I'm using an array and then turning it back into a single string, because I think this is generally more efficient.