Skip to content

Commit

Permalink
Merge 6e0693e into d70b90b
Browse files Browse the repository at this point in the history
  • Loading branch information
vorce committed Oct 8, 2019
2 parents d70b90b + 6e0693e commit 5d2cc03
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 5 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Implementations of some (persistent) data structures for fun and learning. I don
- [Red-black Tree](lib/red_black_tree.ex)
- [Sorted set](lib/sorted_set.ex)
- [Cuckoo filter](lib/cuckoo_filter.ex)
- [Maybe](lib/maybe.ex)

## Example usage

Expand Down
28 changes: 28 additions & 0 deletions lib/maybe.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
defmodule Dasie.Maybe do
@moduledoc """
Represent something empty/missing or not. Also known as Optional in some languages.
This is a pretty contrived thing, but wanted to see how it would look :)
Another take would be to use a single or zero element list.
"""
defstruct value: nil

@type t :: %__MODULE__{
value: any
}

@spec of(value :: any) :: __MODULE__.t()
def of(value), do: %__MODULE__{value: value}

@spec present?(any) :: boolean
def present?(%__MODULE__{value: nil}), do: false
def present?(nil), do: false
def present?(_), do: true

@doc """
If a value is present in this Maybe, returns `{:ok, value}`, otherwise returns `{:error, :no_value}`.
"""
@spec get(maybe :: __MODULE__.t()) :: {:ok, any} | {:error, :no_value}
def get(%__MODULE__{value: nil}), do: {:error, :no_value}
def get(%__MODULE__{value: val}), do: {:ok, val}
end
10 changes: 5 additions & 5 deletions lib/trie.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ defmodule Dasie.Trie do
count: 1

@type t :: %__MODULE__{
children: list(t),
data: any,
terminates?: boolean,
count: integer
}
children: list(t),
data: any,
terminates?: boolean,
count: integer
}

@doc "Creates a new trie"
@spec new() :: __MODULE__.t()
Expand Down
37 changes: 37 additions & 0 deletions test/maybe_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
defmodule Dasie.MaybeTest do
use ExUnit.Case

alias Dasie.Maybe

describe "present?/1" do
test "maybe with value" do
thing = Maybe.of(:something)
assert Maybe.present?(thing)
end

test "maybe with no value" do
thing = Maybe.of(nil)
refute Maybe.present?(thing)
end

test "raw nil" do
refute Maybe.present?(nil)
end

test "raw value" do
assert Maybe.present?(1)
end
end

describe "get/1" do
test "maybe with value" do
thing = Maybe.of(:something)
assert Maybe.get(thing) == {:ok, thing.value}
end

test "maybe with no value" do
thing = Maybe.of(nil)
assert Maybe.get(thing) == {:error, :no_value}
end
end
end

0 comments on commit 5d2cc03

Please sign in to comment.