Functional programming 如何处理Nim中的选项类型?

Functional programming 如何处理Nim中的选项类型?,functional-programming,optional,nim-lang,Functional Programming,Optional,Nim Lang,假设我有一个签名为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"

假设我有一个签名为
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来实现这一点,但我不确定它如何与内置选项模块配合使用:

示例代码:

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"

我刚刚注意到,
选项
有以下步骤:

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