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.
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
for
loop. But the whole point of the program is imperative - printing - so there is no reason not to do this.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.