【问题标题】:Using a default value for a function parameter which depends of other parameter对依赖于其他参数的函数参数使用默认值
【发布时间】:2022-11-14 08:30:25
【问题描述】:

我想创建一个脚本,它接受一个输入文件和一个可选的输出文件。当您不传递输出文件时,脚本使用与输入相同的文件名,但扩展名已更改。我不知道如何编写更改扩展名的默认参数。

#!/usr/bin/env raku

unit sub MAIN(
  Str $input where *.IO.f, #= input file
  Str $output = $input.IO.extension("txt"), #= output file
  Bool :$copy, #= copy file
  Bool :$move, #= move file
);

不幸的是,这不起作用:

No such method 'IO' for invocant of type 'VMNull'
  in block <unit> at ./copy.raku line 5

我怎么能做这样的事情?

【问题讨论】:

  • 这看起来很像一个错误。
  • 是的,看起来很像一些奇怪的代码生成/绑定/调度错误。看起来删除 #= 字符串有一个有益的效果。
  • 谢谢!。我删除了评论作为解决方法。

标签: raku


【解决方案1】:

错误消息不太好,但程序无法正常工作是预期的,因为您在签名中

Str $output = $input.IO.extension("txt")

但右侧返回具有该扩展名的IO::Path 对象,但$output 被键入为字符串。那是一个错误:

>>> my Str $s = "file.csv".IO.extension("txt")
Type check failed in assignment to $s; expected Str but got IO::Path (IO::Path.new("file.t...)
  in block <unit> at <unknown file> line 1
>>> sub fun(Str $inp, Str $out = $inp.IO.extension("txt")) { }
&fun

>>> fun "file.csv"
Type check failed in binding to parameter '$out'; expected Str but got IO::Path (IO::Path.new("file.t...)
  in sub fun at <unknown file> line 1
  in block <unit> at <unknown file> line 1

有时编译器会检测到不兼容的默认值:

>>> sub yes(Str $s = 3) { }
===SORRY!=== Error while compiling:
Default value '3' will never bind to a parameter of type Str
------> sub yes(Str $s = 3⏏) { }
    expecting any of:
        constraint

但是您所拥有的远非文字,因此运行时检测。

要修复它,您可以

  • 更改为Str() $output = $inp.IO.extension("txt"),其中Str() 表示“接受任何对象,然后将其转换为Str”。所以$output 最终会成为像"file.txt" 这样的字符串,在MAIN 中可用。

    • 类似的替代方案:Str $output = $inp.IO.extension("txt").Str,但在Str 中重复出现。
  • 更改为IO::Path() $output = $inp.IO.extension("txt")。同样,这将转换为IO::Path 对象收到的任何内容,因此,例如,您将在$output 中获得"file.txt".IO。如果您这样做,您可能希望对$input 执行相同的操作以保持一致性。由于IO::Path 对象对.IO 是幂等的(在eqv 意义上),代码的其他部分不需要更改。

【讨论】:

    猜你喜欢
    • 2013-11-18
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    相关资源
    最近更新 更多