>假设我有一个带有签名proc foo(): Option[int]
的函数,我设置了var x: Option[int] = foo()
。
如何根据x
是some
还是none
执行不同的操作?
例如,在Scala中,我可以做:
x match {
case Some(a) => println(s"Your number is $a")
case None => println("You don't have a number")
}
甚至:
println(x.map(y => s"Your number is $y").getOrElse("You don't have a number"))
到目前为止,我已经想出了:
if x.isSome():
echo("Your number is ", x.get())
else:
echo("You don't have a number")
这看起来不像是好的功能风格。还有更好的吗?
我刚刚注意到options
具有以下过程:
proc get*[T](self: Option[T], otherwise: T): T =
## Returns the contents of this option or `otherwise` if the option is none.
这就像 Scala 中的getOrElse
,所以使用 map
和 get
,我们可以做一些类似于我的例子的事情:
import options
proc maybeNumber(x: Option[int]): string =
x.map(proc(y: int): string = "Your number is " & $y)
.get("You don't have a number")
let a = some(1)
let b = none(int)
echo(maybeNumber(a))
echo(maybeNumber(b))
输出:
Your number is 1
You don't have a number
你可以为此使用肉饼,但我不确定它如何与内置选项模块一起工作:https://github.com/andreaferretti/patty
示例代码:
import patty
type
OptionKind = enum Some, None
Option[t] = object
val: t
kind: OptionKind
var x = Option[int](val: 10, kind: Some)
match x:
Some(a): echo "Your number is ", a
Nothing: echo "You don't have a number"
我的解决方案使用融合/匹配和选项
import options
import strformat
import fusion/matching
proc makeDisplayText(s: Option[string]): string =
result = case s
of Some(@val): fmt"The result is: {val}"
of None(): "no value input"
else: "cant parse input "