Linux tac函数的F#副本(tac与cat相反)

时间:2017-10-09 12:15:45

标签: .net f# f#-interactive

这个问题,我现在已经挣扎了很长一段时间。我不明白如何从末尾读取文件中的行,并使函数占用1或2个文件路径(第2个必须是可选的) 任何建议......

let checkIfExists path = 
      if System.IO.File.Exists path 
      then true
      else false
let tac path = 
      if checkIfExists path =
      then
            System.IO.File.ReadAllLines |> Seq.rev
            0
      else
            printfn “no such file exists”
            -1

1 个答案:

答案 0 :(得分:1)

通常,最好显示一些示例代码(即使它不起作用)。以最简单的形式,以下功能可以满足您的需求:

open System
open System.IO
let reverseLines f =
  File.ReadAllLines f
  |> Seq.rev

关于接受可选参数,我认为最好通过CLI库来完成,例如Argu,它应该处理tac的其他参数。

修改

我刚刚将反向功能更改为Array.rev,因为在这种情况下更容易处理。

这个程序有两个部分,你可以看到reverseLines基本上没有变化。然后在main中我们检查有多少个参数,并将文件名提取到fName。在第二部分中,我们直接在文件名上调用File.exists,如果是true,我们运行reverseLines,并将输出传递到控制台。

您可以将此程序作为.\lineReverser.exe C:\tmp\FileToBeReversed.txt运行。如果您只是在fsx文件中进行测试,只需将main分解为另一个函数,它将完全相同。

答案的第一部分中的其他所有内容仍然存在,有关F#的一些好书包括:Expert F# 4.0Get Programming with F#。如果你只是通过fsharpforfunandprofit的介绍系列部分,那将清除你可能遇到的许多问题。

module SOAnswers171016
open System
open System.IO

let reverseLines f =
  File.ReadAllLines f
  |> Array.rev

[<EntryPoint>]
let main argv =
    let fName = //check how many arguments are passed and extract the filename if there is only one argument 
        match argv.Length with
        | 0 -> failwith "Please specify a file name!"
        | 1 -> argv.[0]
        | _ -> failwith "Too many parameters!"  //you could handle the two file parameter case here 

    match File.Exists(fName) with
    | true -> reverseLines fName |> Array.iter Console.WriteLine //we are just piping the reversed lines to the console
    | false -> failwith "File doesn't exist!"

    0 // return an integer exit code