如何处理 Nim 中的选项类型?
How to handle option types in Nim?
假设我有一个签名为 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")
这看起来不像是好的功能样式。还有更好的吗?
您可以为此使用 patty,但我不确定它如何与内置选项模块一起使用: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"
我刚刚注意到 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
我使用 fusion/matching 和选项
的解决方案
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 "
假设我有一个签名为 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")
这看起来不像是好的功能样式。还有更好的吗?
您可以为此使用 patty,但我不确定它如何与内置选项模块一起使用: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"
我刚刚注意到 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
我使用 fusion/matching 和选项
的解决方案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 "