From c49d038540f8eb36bf727aa27cd64e77118ef8df Mon Sep 17 00:00:00 2001 From: ffranr Date: Fri, 25 Oct 2024 16:29:16 +0100 Subject: [PATCH 1/2] fn: add OptionFromPtr function Add a function `OptionFromPtr` that constructs an `Option` from a pointer. The function signature is: `OptionFromPtr : *A -> Option[A]`. This utility has proven useful in the taproot-assets project. --- fn/option.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/fn/option.go b/fn/option.go index 797f3a0ff0..60e64cf3c5 100644 --- a/fn/option.go +++ b/fn/option.go @@ -26,6 +26,17 @@ func None[A any]() Option[A] { return Option[A]{} } +// OptionFromPtr constructs an option from a pointer. +// +// OptionFromPtr : *A -> Option[A]. +func OptionFromPtr[A any](a *A) Option[A] { + if a == nil { + return None[A]() + } + + return Some[A](*a) +} + // ElimOption is the universal Option eliminator. It can be used to safely // handle all possible values inside the Option by supplying two continuations. // From 71298f7614368e1aecdbb2f5cb1993cec6bf1cff Mon Sep 17 00:00:00 2001 From: ffranr Date: Fri, 25 Oct 2024 16:30:59 +0100 Subject: [PATCH 2/2] fn: fix documentation comment for Option Remove the type generic from the `Option` type struct in the doc comment. --- fn/option.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fn/option.go b/fn/option.go index 60e64cf3c5..f1a6c858c6 100644 --- a/fn/option.go +++ b/fn/option.go @@ -2,8 +2,8 @@ package fn import "testing" -// Option[A] represents a value which may or may not be there. This is very -// often preferable to nil-able pointers. +// Option represents a value which may or may not be there. This is very often +// preferable to nil-able pointers. type Option[A any] struct { isSome bool some A