Skip to content

Handle responses and options with chain- operators #85

@hugoclrd

Description

@hugoclrd

Context

With match <response> or match <optional>, a common pattern is to handle the ok or some value if any, but to return the err or none otherwise.

(match (contract-call? ...)
  response (handle response)
  error-code (err error) ;; simply forward the error
)

(match (map-get? ...)
  value (handle value)
  none ;; forward the none
)

Potential solution(s)

(chain_ok <response> ...handlers), (chain_some <optional> ...handlers)

Inspired by Rust's <result>.map(), or .and_then(), Clarity could have similar helpers.

I suggest the chain- helpers that would accept a response or optional as a first argument, followed by 1 to N function calls or lambdas (#56) to handle and forward the response or optional

(chain-ok (contract-call? .contract get-response) ;; the contract-call returns (response _  uint)
  (handle-ok-0) ;; must return (response _  uint)
  (handle-ok-1) ;; must return (response _  uint)
  ;; variadic number of handlers/lambdas
  (lamdba (x int) (ok (+ x 1))
) 
(chain (map-get? <key>)
  (handle-if-some) ;; must return (optional _)
   ;; variadic number of handlers/lambdas
  (lamdba (x int) (some (+ x 1))
) 

Idea: we could also have a chain-err helper to catch an error and forward another one.

Generic chain

Just like (match response|optional), we could have a generic `(chain response|optional)

Real world examples

// To do

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions