3

Say I have a function with signature proc foo(): Option[int] and I set var x: Option[int] = foo().

How do I perform a different action depending on whether x is some or none?

For example in Scala I could do:

x match {
  case Some(a) => println(s"Your number is $a")
  case None => println("You don't have a number")
}

or even:

println(x.map(y => s"Your number is $y").getOrElse("You don't have a number"))

So far I have come up with:

if x.isSome():
  echo("Your number is ", x.get())
else:
  echo("You don't have a number")

Which doesn't look like good functional style. Is there something better?

Imran
  • 12,950
  • 8
  • 64
  • 79

3 Answers3

3

I just noticed that options has the following procedure:

proc get*[T](self: Option[T], otherwise: T): T =
  ## Returns the contents of this option or `otherwise` if the option is none.

which is like getOrElse in Scala, so using map and get, we could do something similar to my example:

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))

Output:

Your number is 1
You don't have a number
Imran
  • 12,950
  • 8
  • 64
  • 79
2

You could use patty for this, but I'm not sure how it works with the built-in options module: https://github.com/andreaferretti/patty

Example code:

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"
def-
  • 5,275
  • 20
  • 18
1

My solution using the fusion/matching, and option

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 "

georgehu
  • 186
  • 1
  • 12