【问题标题】:How to handle option types in Nim?如何处理 Nim 中的选项类型?
【发布时间】:2018-01-23 19:44:18
【问题描述】:

假设我有一个带有签名proc foo(): Option[int] 的函数,我设置了var x: Option[int] = foo()

如何根据xsome 还是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")

这看起来不像是好的功能风格。有更好的吗?

【问题讨论】:

    标签: functional-programming optional nim-lang


    【解决方案1】:

    您可以为此使用 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"
    

    【讨论】:

      【解决方案2】:

      我刚刚注意到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,所以使用 mapget,我们可以做一些类似于我的例子的事情:

      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
      

      【讨论】:

        【解决方案3】:

        我使用融合/匹配和选项的解决方案

        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 "
        
        

        【讨论】:

          猜你喜欢
          • 2012-03-31
          • 2016-12-24
          • 1970-01-01
          • 2023-02-04
          • 2021-04-01
          • 2021-01-09
          • 1970-01-01
          • 1970-01-01
          • 2022-06-30
          相关资源
          最近更新 更多