.net F#复制Linux tac函数(tac与cat相反)
我为这个问题挣扎了很长一段时间。我不明白如何从文件的末尾读取行,并使函数采用1或2个文件路径(第2个路径必须是可选的) 任何建议.net F#复制Linux tac函数(tac与cat相反),.net,f#,f#-interactive,.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.ReadA
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
通常,最好显示一些示例代码(即使它不起作用)。以最简单的形式,以下函数将执行您想要的操作:
open System
open System.IO
let reverseLines f =
File.ReadAllLines f
|> Seq.rev
关于使用可选参数,我认为最好通过CLI库来实现,比如,它还应该处理tac
的其他参数
编辑:
我刚刚将reverse函数改为Array.rev
,因为在这种情况下更容易处理
这个程序有两个部分,您可以看到反向线
基本上没有变化。然后在main
中检查有多少个参数,并将文件名提取到fName
中。在第二部分中,我们直接调用文件名上的File.exists
,如果是true
,则运行reverseLines,并将输出导入控制台
您只需以\lineReverser.exe C:\tmp\FileToBeReversed.txt
的形式运行此程序即可。如果您只是在一个fsx文件中进行测试,只需将main分解成另一个函数,它的工作原理将完全相同
答案第一部分的其他内容仍然有效,一些关于F的好书包括:。如果你只看了介绍系列的部分,你可能会有很多问题
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
模块SOAnswers171016
开放系统
开放系统
让我们把线倒转f=
File.ReadAllLines f
|>Array.rev
[]
让主argv=
让fName=//检查传递了多少个参数,如果只有一个参数,则提取文件名
将argv.Length与
|0->failwith“请指定文件名!”
|1->argv[0]
|->failwith“参数太多!”//您可以在这里处理两个文件参数的情况
将文件.Exists(fName)与匹配
|true->reverseLines fName |>Array.iter Console.WriteLine//我们只是将反向的线路连接到控制台
|false->failwith“文件不存在!”
0//返回整数退出代码
这是课堂作业吗?如果是这样的话,记住告诉教授是谁帮你完成了作业是很重要的,这样他/她就可以看到你能理解什么,以及你在做什么。(也因为这是诚实的做法。)如果这不是类赋值,那么您能解释一下为什么需要函数接受1或2个参数吗?这只是函数编程模块的一个实践练习。@LioxaZAICHIK FP语言是基于表达式的,它们总是返回一些东西,您的if
表达式返回0或-1,并丢弃真分支中的反向行。因此,您将得到一个ignore
警告。我会更新答案。这种方法会给我一条忽略消息,并且不会对文件上的文本执行任何操作。你能显示你的代码吗?只需编辑您的原始邮件。@LioxaZAICHIK查看我的编辑。