JuliaFunctional / DataTypesBasic.jl

Option, Try, Either, and some more common basic DataTypes
MIT License
12 stars 4 forks source link

DataTypesBasic

Stable Dev Build Status Coverage

This package defines julia implementations for the common types Option (aka Maybe), Either and Try, as well as one extra type ContextManager which mimics Python's with-ContextManager.

Usage

Here an example using Try to handle errors programmatically. Similar to Option, a Try is either a Const, denoting an error, or an Identity value, which denotes success.

using DataTypesBasic  # defines Try

@Try div(1, 0)  # Const(Thrown(DivideError()))
@Try div(8, 3)  # Identity(2)

Using another helper package Monadic. We can combine these into nice syntax.

using Monadic  # defines @monadic

# flatmap is also defined in TypeClasses.jl
flatmap(f, x) = Iterators.flatten(map(f, x))
tryit = @monadic map flatmap begin
  a = @Try div(8, 3)
  b = @Try isodd(a) ? 100 + a : error("fail")
  @pure a, b
end
# Const(Thrown(ErrorException("fail")))

For more details check out the documentation.