Repository: expede/algae
Branch: main
Commit: 8e9e2487b2d7
Files: 80
Total size: 113.8 KB
Directory structure:
gitextract_pg39seh_/
├── .credo.exs
├── .envrc
├── .github/
│ ├── CODE_OF_CONDUCT.md
│ ├── PULL_REQUEST_TEMPLATE.md
│ └── workflows/
│ ├── ci.yaml
│ └── greetings.yml
├── .gitignore
├── .tool-versions
├── LICENSE
├── README.md
├── brand/
│ └── LOGO_LICENSE
├── lib/
│ ├── algae/
│ │ ├── either.ex
│ │ ├── free.ex
│ │ ├── id/
│ │ │ ├── applicative.ex
│ │ │ ├── apply.ex
│ │ │ ├── chain.ex
│ │ │ ├── comonad.ex
│ │ │ ├── extend.ex
│ │ │ ├── foldable.ex
│ │ │ ├── functor.ex
│ │ │ ├── generator.ex
│ │ │ ├── monad.ex
│ │ │ ├── monoid.ex
│ │ │ ├── ord.ex
│ │ │ ├── semigroup.ex
│ │ │ ├── setoid.ex
│ │ │ └── traversable.ex
│ │ ├── id.ex
│ │ ├── internal/
│ │ │ └── needs_explicit_default_error.ex
│ │ ├── internal.ex
│ │ ├── maybe.ex
│ │ ├── reader/
│ │ │ ├── applicative.ex
│ │ │ ├── apply.ex
│ │ │ ├── chain.ex
│ │ │ ├── functor.ex
│ │ │ ├── generator.ex
│ │ │ └── monad.ex
│ │ ├── reader.ex
│ │ ├── state/
│ │ │ ├── applicative.ex
│ │ │ ├── apply.ex
│ │ │ ├── chain.ex
│ │ │ ├── functor.ex
│ │ │ ├── generator.ex
│ │ │ └── monad.ex
│ │ ├── state.ex
│ │ ├── tree/
│ │ │ ├── binary_search/
│ │ │ │ ├── applicative.ex
│ │ │ │ ├── apply.ex
│ │ │ │ ├── chain.ex
│ │ │ │ ├── extend.ex
│ │ │ │ ├── foldable.ex
│ │ │ │ ├── functor.ex
│ │ │ │ ├── generator.ex
│ │ │ │ ├── monad.ex
│ │ │ │ ├── monoid.ex
│ │ │ │ ├── ord.ex
│ │ │ │ ├── semigroup.ex
│ │ │ │ └── setoid.ex
│ │ │ ├── binary_search.ex
│ │ │ ├── rose/
│ │ │ │ ├── applicative.ex
│ │ │ │ ├── apply.ex
│ │ │ │ ├── chain.ex
│ │ │ │ ├── foldable.ex
│ │ │ │ ├── functor.ex
│ │ │ │ ├── generator.ex
│ │ │ │ └── monad.ex
│ │ │ └── rose.ex
│ │ ├── writer/
│ │ │ ├── applicative.ex
│ │ │ ├── apply.ex
│ │ │ ├── chain.ex
│ │ │ ├── functor.ex
│ │ │ ├── generator.ex
│ │ │ └── monad.ex
│ │ └── writer.ex
│ └── algae.ex
├── mix.exs
├── shell.nix
└── test/
├── algae_dsl_aliasing_test.exs
├── algae_test.exs
├── support/
│ └── example.ex
└── test_helper.exs
================================================
FILE CONTENTS
================================================
================================================
FILE: .credo.exs
================================================
%{
configs: [
%{
name: "default",
files: %{
included: ["lib/", "test"],
excluded: []
},
checks: [
{Credo.Check.Consistency.TabsOrSpaces},
{Credo.Check.Design.AliasUsage, false},
{Credo.Check.Readability.MaxLineLength, priority: :low, max_length: 100}
]
}
]
}
================================================
FILE: .envrc
================================================
use nix
export MIX_HOME=$(pwd)/.mix
export PATH=$PATH:$(pwd)/.mix/escripts
================================================
FILE: .github/CODE_OF_CONDUCT.md
================================================
# Code of Conduct
## 1. Purpose
A primary goal of Witchcrafters is to be inclusive to the largest number of contributors, with the most varied and diverse backgrounds possible. As such, we are committed to providing a friendly, safe and welcoming environment for all, regardless of gender, sexual orientation, ability, ethnicity, socioeconomic status, and religion (or lack thereof).
This code of conduct outlines our expectations for all those who participate in our community, as well as the consequences for unacceptable behavior.
We invite all those who participate in Witchcrafters to help us create safe and positive experiences for everyone.
## 2. Open Source Citizenship
A supplemental goal of this Code of Conduct is to increase open source citizenship by encouraging participants to recognize and strengthen the relationships between our actions and their effects on our community.
Communities mirror the societies in which they exist and positive action is essential to counteract the many forms of inequality and abuses of power that exist in society.
If you see someone who is making an extra effort to ensure our community is welcoming, friendly, and encourages all participants to contribute to the fullest extent, we want to know.
## 3. Expected Behavior
The following behaviors are expected and requested of all community members:
* Participate in an authentic and active way. In doing so, you contribute to the health and longevity of this community.
* Exercise consideration and respect in your speech and actions.
* Attempt collaboration before conflict.
* Refrain from demeaning, discriminatory, or harassing behavior and speech.
* Be mindful of your surroundings and of your fellow participants. Alert community leaders if you notice a dangerous situation, someone in distress, or violations of this Code of Conduct, even if they seem inconsequential.
* Remember that community event venues may be shared with members of the public; please be respectful to all patrons of these locations.
## 4. Unacceptable Behavior
The following behaviors are considered harassment and are unacceptable within our community:
* Violence, threats of violence or violent language directed against another person.
* Sexist, racist, homophobic, transphobic, ableist or otherwise discriminatory jokes and language.
* Posting or displaying sexually explicit or violent material.
* Posting or threatening to post other people’s personally identifying information ("doxing").
* Personal insults, particularly those related to gender, sexual orientation, race, religion, or disability.
* Inappropriate photography or recording.
* Inappropriate physical contact. You should have someone’s consent before touching them.
* Unwelcome sexual attention. This includes, sexualized comments or jokes; inappropriate touching, groping, and unwelcomed sexual advances.
* Deliberate intimidation, stalking or following (online or in person).
* Advocating for, or encouraging, any of the above behavior.
* Sustained disruption of community events, including talks and presentations.
## 5. Consequences of Unacceptable Behavior
Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated.
Anyone asked to stop unacceptable behavior is expected to comply immediately.
If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event).
## 6. Reporting Guidelines
If you are subject to or witness unacceptable behavior, or have any other concerns, please notify a community organizer as soon as possible. hello@brooklynzelenka.com.
Additionally, community organizers are available to help community members engage with local law enforcement or to otherwise help those experiencing unacceptable behavior feel safe. In the context of in-person events, organizers will also provide escorts as desired by the person experiencing distress.
## 7. Addressing Grievances
If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify the maintainers with a concise description of your grievance. Your grievance will be handled in accordance with our existing governing policies.
## 8. Scope
We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues–online and in-person–as well as in all one-on-one communications pertaining to community business.
This code of conduct and its related procedures also applies to unacceptable behavior occurring outside the scope of community activities when such behavior has the potential to adversely affect the safety and well-being of community members.
## 9. Contact info
hello@fission.codes
## 10. License and attribution
This Code of Conduct is distributed under a [Creative Commons Attribution-ShareAlike license](http://creativecommons.org/licenses/by-sa/3.0/).
Portions of text derived from the [Django Code of Conduct](https://www.djangoproject.com/conduct/) and the [Geek Feminism Anti-Harassment Policy](http://geekfeminism.wikia.com/wiki/Conference_anti-harassment/Policy).
Retrieved on November 22, 2016 from [http://citizencodeofconduct.org/](http://citizencodeofconduct.org/)
================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
A similar PR may already be submitted!
Please search among the [Pull request](../) before creating one.
Thanks for submitting a pull request! Please provide enough information so that others can review your pull request:
For more information, see the `CONTRIBUTING` guide.
## Summary
<!-- Summary of the PR -->
This PR fixes/implements the following **bugs/features**
* [ ] Bug 1
* [ ] Bug 2
* [ ] Feature 1
* [ ] Feature 2
* [ ] Breaking changes
<!-- You can skip this if you're fixing a typo or adding an app to the Showcase. -->
Explain the **motivation** for making this change. What existing problem does the pull request solve?
<!-- Example: When "Adding a function to do X", explain why it is necessary to have a way to do X. -->
## Test plan (required)
Demonstrate the code is solid. Example: The exact commands you ran and their output, screenshots / videos if the pull request changes UI.
<!-- Make sure tests pass on Circle CI. -->
## Closing issues
<!-- Put `closes #XXXX` in your comment to auto-close the issue that your PR fixes (if such). -->
Fixes #
## After Merge
* [ ] Does this change invalidate any docs or tutorials? _If so ensure the changes needed are either made or recorded_
* [ ] Does this change require a release to be made? Is so please create and deploy the release
================================================
FILE: .github/workflows/ci.yaml
================================================
on:
push: { "branches": [ "main" ] }
pull_request: { "branches": [ "main" ] }
jobs:
test:
runs-on: ubuntu-latest
name: OTP ${{matrix.otp}} / Elixir ${{matrix.elixir}}
strategy:
matrix:
otp: ['23.0']
elixir: ['1.11.3']
steps:
- uses: actions/checkout@v2
- uses: erlef/setup-elixir@v1
with:
otp-version: ${{matrix.otp}}
elixir-version: ${{matrix.elixir}}
- run: MIX_ENV=test mix deps.get
- run: MIX_ENV=test mix test
- run: MIX_ENV=test mix credo --strict
================================================
FILE: .github/workflows/greetings.yml
================================================
name: Greetings
on: [pull_request, issues]
jobs:
greeting:
runs-on: ubuntu-latest
steps:
- uses: actions/first-interaction@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
issue-message: 'Thank you for submitting an issue! It means a lot that you took the time -- it helps us be better 🙏'
pr-message: "Thank you for submitting a PR 🎉 It's very appreciated!"
================================================
FILE: .gitignore
================================================
/_build
/cover
/deps
/doc
erl_crash.dump
*.ez
*.beam
.DS_Store
.mix
================================================
FILE: .tool-versions
================================================
erlang 24.2
elixir 1.13.2
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2017 Brooklyn Zelenka
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================

[](https://travis-ci.org/expede/algae) [](http://inch-ci.org/github/expede/algae) [](https://beta.hexfaktor.org/github/expede/algae) [](https://hex.pm/packages/algae) [](http://hexdocs.pm/algae/) [](https://github.com/expede/algae/blob/master/LICENSE)
Algae provides a boilerplate-avoiding DSL for defining algebraic data types (ADTs),
plus several common structures
# Quickstart
Add Algae to your list of dependencies in `mix.exs`:
```elixir
def deps do
[{:algae, "~> 1.2"}]
end
```
# Table of Contents
- [Product Builder](#product-builder)
- [Definition DSL](#definition-dsl)
- [Constructor](#constructor)
- [Empty Tag](#empty-tag)
- [Sum Builder](#sum-builder)
- [Default Constructor](#default-constructor)
- [Tagged Unions](#tagged-unions)
- [A Sampling of ADTs](#a-sampling-of-adts)
- [`Id`](#algaeid)
- [`Maybe`](#algaemaybe)
- [`Tree.BinarySearch`](#algaetreebinarysearch)
---
> **NOTE**
> Please `import Algae` before trying out the examples below.
> The samples assume that is has already been done to remove
> the unnecessary clutter.
---
# Product Builder
Build a product type
Includes:
* Struct
* Type definition
* Constructor function (for piping and defaults)
* Implicit defaults for simple values
## Definition DSL
For convenience, several variants of the DSL are available.
### Standard
```elixir
defmodule Player do
# =============== #
# Data Definition #
# =============== #
defdata do
name :: String.t()
hit_points :: non_neg_integer()
experience :: non_neg_integer()
end
# =================== #
# Rest of Module #
# (business as usual) #
# =================== #
@spec attack(t(), t()) :: {t(), t()}
def attack(%{experience: xp} = player, %{hit_points: hp} = target) do
{
%{player | experience: xp + 50},
%{target | hit_points: hp - 10}
}
end
end
#=> %Player{name: "Sir Bob", hit_points: 10, experience: 500}
```
### Single Field Shorthand
Without any fields specified, Algae will default to a single field with
the same name as the module (essentially a "wrapper type"). You must still
provide the type for this field, however.
Embedded in another module:
```elixir
defmodule Id do
defdata any()
end
%Id{}
#=> %Id{id: nil}
```
Standalone:
```elixir
defdata Wrapper :: any()
%Wrapper{}
#=> %Wrapper{wrapper: nil}
```
## Constructor
A helper function, especially useful for piping. The order of arguments is
the same as the order that they are defined in.
```elixir
defmodule Person do
defdata do
name :: String.t()
age :: non_neg_integer()
end
end
Person.new("Rachel Weintraub")
#=> %Person{
# name: "Rachel Weintraub",
# age: 0
# }
```
### Constructor Defaults
Fields will automatically default to a sensible value (a typical "zero" for
that datatype). For example, `non_neg_integer()` will default to `0`,
and `String.t()` will default to `""`.
You may also overwrite these defaults with the `\\` syntax.
```elixir
defmodule Pet do
defdata do
name :: String.t()
leg_count :: non_neg_integer() \\ 4
end
end
Pet.new("Crookshanks")
#=> %Pet{
# name: "Crookshanks",
# leg_count: 4
# }
Pet.new("Paul the Psychic Octopus", 8)
#=> %Pet{
# name: "Paul the Psychic Octopus",
# leg_count: 8
# }
```
This overwriting syntax is _required_ for complex types:
```elixir
defdata Grocery do
item :: {String.t(), integer(), boolean()} \\ {"Orange", 4, false}
end
Grocery.new()
#=> %Grocery{
# item: {"Orange", 4, false}
# }
```
### Overwrite Constructor
The `new` constructor function may be overwritten.
```elixir
defmodule Constant do
defdata :: fun()
def new(value), do: %Constant{constant: fn _ -> value end}
end
fourty_two = Constant.new(42)
fourty_two.constant.(33)
#=> 42
```
## Empty Tag
An empty type (with no fields) is definable using the `none`() type
```elixir
defmodule Nothing do
defdata none()
end
Nothing.new()
#=> %Nothing{}
```
# Sum Builder
Build a sum (coproduct) type from product types
```elixir
defmodule Light do
# ============== #
# Sum Definition #
# ============== #
defsum do
defdata Red :: none()
defdata Yellow :: none()
defdata Green :: none()
end
# =================== #
# Rest of Module #
# (business as usual) #
# =================== #
def from_number(1), do: %Light.Red{}
def from_number(2), do: %Light.Yellow{}
def from_number(3), do: %Light.Green{}
end
Light.new()
#=> %Light.Red{}
```
## Embedded Products
Data with multiple fields can be defined directly as part of a sum
```elixir
defmodule Pet do
defsum do
defdata Cat do
name :: String.t()
claw_sharpness :: String.t()
end
defdata Dog do
name :: String.t()
bark_loudness :: non_neg_integer()
end
end
end
```
## Default Constructor
The first `defdata`'s constructor will be the default constructor for the sum
```elixir
defmodule Maybe do
defsum do
defdata Nothing :: none()
defdata Just :: any()
end
end
Maybe.new()
#=> %Maybe.Nothing{}
```
## Tagged Unions
Sums join existing types with tags: new types to help distinguish the context
that they are in (the sum type)
```elixir
defdata Book :: String.t() \\ "War and Peace"
defdata Video :: String.t() \\ "2001: A Space Odyssey"
defmodule Media do
defsum do
defdata Paper :: Book.t()
defdata Film :: Video.t() \\ Video.new("A Clockwork Orange")
end
end
media = Media.new()
#=> %Paper{
# paper: %Book{
# book: "War and Peace"
# }
# }
```
# A Sampling of ADTs
See [complete docs](https://hexdocs.pm/algae) for more
## `Algae.Id`
The simplest ADT: a simple wrapper for some data
```elixir
%Algae.Id{id: "hi!"}
```
## `Algae.Maybe`
Maybe represents the presence or absence of something.
Please note that `nil` is actually a value, as it can be passed to functions!
`nil` is not bottom!
```elixir
Algae.Maybe.new()
#=> %Algae.Maybe.Nothing{}
Algae.Maybe.new(42)
#=> %Algae.Maybe.Just{just: 42}
```
## `Tree.BinarySearch`
```elixir
alias Algae.Tree.BinarySearch, as: BTree
# 42
# / \
# 77 1234
# / \
# 98 32
BTree.Branch.new(
42,
BTree.Branch.new(77),
BTree.Branch.new(
1234,
BTree.Branch.new(98),
BTree.Branch.new(32)
)
)
#=> %Algae.Tree.BinarySearch.Branch{
# value: 42,
# left: %Algae.Tree.BinarySearch.Branch{
# value: 77,
# left: %Algae.Tree.BinarySearch.Empty{},
# right: %Algae.Tree.BinarySearch.Empty{}
# },
# right: %Algae.Tree.BinarySearch.Branch{
# value: 1234,
# left: %Algae.Tree.BinarySearch.Branch{
# value: 98,
# left: %Algae.Tree.BinarySearch.Empty{},
# right: %Algae.Tree.BinarySearch.Empty{}
# },
# right: %Algae.Tree.BinarySearch.Branch{
# value: 32,
# left: %Algae.Tree.BinarySearch.Empty{},
# right: %Algae.Tree.BinarySearch.Empty{}
# }
# }
# }
```
================================================
FILE: brand/LOGO_LICENSE
================================================
ORIGINAL AUTHOR ATTRIBUTION: Gabriele Kothe-Heinrich
DESCRIPTION: Halidrys siliquosa (L.) Lyngb., herbarium sheet. Collected 1985-09-10, Heligoland (Germany)
SOURCE: https://commons.wikimedia.org/wiki/File:Halidrys_siliquosa_Helgoland.JPG
MODIFIED: Yes
License
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
1. Definitions
"Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License.
"Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined below) for the purposes of this License.
"Creative Commons Compatible License" means a license that is listed at https://creativecommons.org/compatiblelicenses that has been approved by Creative Commons as being essentially equivalent to this License, including, at a minimum, because that license: (i) contains terms that have the same purpose, meaning and effect as the License Elements of this License; and, (ii) explicitly permits the relicensing of adaptations of works made available under that license under this License or a Creative Commons jurisdiction license with the same License Elements as this License.
"Distribute" means to make available to the public the original and copies of the Work or Adaptation, as appropriate, through sale or other transfer of ownership.
"License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike.
"Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License.
"Original Author" means, in the case of a literary or artistic work, the individual, individuals, entity or entities who created the Work or if no individual or entity can be identified, the publisher; and in addition (i) in the case of a performance the actors, singers, musicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or otherwise perform literary or artistic works or expressions of folklore; (ii) in the case of a phonogram the producer being the person or legal entity who first fixes the sounds of a performance or other sounds; and, (iii) in the case of broadcasts, the organization that transmits the broadcast.
"Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work.
"You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
"Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images.
"Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium.
2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws.
3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:
to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections;
to create and Reproduce Adaptations provided that any such Adaptation, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "The original work was translated from English to Spanish," or a modification could indicate "The original work has been modified.";
to Distribute and Publicly Perform the Work including as incorporated in Collections; and,
to Distribute and Publicly Perform Adaptations.
For the avoidance of doubt:
Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License;
Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor waives the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; and,
Voluntary License Schemes. The Licensor waives the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License.
The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. Subject to Section 8(f), all rights not expressly granted by Licensor are hereby reserved.
4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:
You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(c), as requested. If You create an Adaptation, upon notice from any Licensor You must, to the extent practicable, remove from the Adaptation any credit as required by Section 4(c), as requested.
You may Distribute or Publicly Perform an Adaptation only under the terms of: (i) this License; (ii) a later version of this License with the same License Elements as this License; (iii) a Creative Commons jurisdiction license (either this or a later license version) that contains the same License Elements as this License (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons Compatible License. If you license the Adaptation under one of the licenses mentioned in (iv), you must comply with the terms of that license. If you license the Adaptation under the terms of any of the licenses mentioned in (i), (ii) or (iii) (the "Applicable License"), you must comply with the terms of the Applicable License generally and the following provisions: (I) You must include a copy of, or the URI for, the Applicable License with every copy of each Adaptation You Distribute or Publicly Perform; (II) You may not offer or impose any terms on the Adaptation that restrict the terms of the Applicable License or the ability of the recipient of the Adaptation to exercise the rights granted to that recipient under the terms of the Applicable License; (III) You must keep intact all notices that refer to the Applicable License and to the disclaimer of warranties with every copy of the Work as included in the Adaptation You Distribute or Publicly Perform; (IV) when You Distribute or Publicly Perform the Adaptation, You may not impose any effective technological measures on the Adaptation that restrict the ability of a recipient of the Adaptation from You to exercise the rights granted to that recipient under the terms of the Applicable License. This Section 4(b) applies to the Adaptation as incorporated in a Collection, but this does not require the Collection apart from the Adaptation itself to be made subject to the terms of the Applicable License.
If You Distribute, or Publicly Perform the Work or any Adaptations or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and (iv) , consistent with Ssection 3(b), in the case of an Adaptation, a credit identifying the use of the Work in the Adaptation (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4(c) may be implemented in any reasonable manner; provided, however, that in the case of a Adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the Adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties.
Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this License (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this License (right to make Adaptations) but not otherwise.
5. Representations, Warranties and Disclaimer
UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. Termination
This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Adaptations or Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.
8. Miscellaneous
Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
Each time You Distribute or Publicly Perform an Adaptation, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.
The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law.
================================================
FILE: lib/algae/either.ex
================================================
defmodule Algae.Either do
@moduledoc ~S"""
Represent branching conditions. These could be different return types,
error vs nominal value, and so on.
## Examples
iex> require Integer
...>
...> even_odd = fn(value) ->
...> if Integer.is_even(value) do
...> Algae.Either.Right.new(value)
...> else
...> Algae.Either.Left.new(value)
...> end
...> end
...>
...> even_odd.(10)
%Algae.Either.Right{right: 10}
...> even_odd.(11)
%Algae.Either.Left{left: 11}
"""
import Algae
defsum do
defdata Left :: any()
defdata Right :: any()
end
end
alias Algae.Either.{Left, Right}
import TypeClass
use Witchcraft
#############
# Generator #
#############
defimpl TypeClass.Property.Generator, for: Algae.Either.Left do
def generate(_) do
[1, 1.1, "", []]
|> Enum.random()
|> TypeClass.Property.Generator.generate()
|> Algae.Either.Left.new()
end
end
defimpl TypeClass.Property.Generator, for: Algae.Either.Right do
def generate(_) do
[1, 1.1, "", []]
|> Enum.random()
|> TypeClass.Property.Generator.generate()
|> Algae.Either.Right.new()
end
end
##########
# Setoid #
##########
definst Witchcraft.Setoid, for: Algae.Either.Left do
def equivalent?(_, %Right{}), do: false
def equivalent?(%Left{left: a}, %Left{left: b}), do: Witchcraft.Setoid.equivalent?(a, b)
end
definst Witchcraft.Setoid, for: Algae.Either.Right do
def equivalent?(_, %Left{}), do: false
def equivalent?(%Right{right: a}, %Right{right: b}), do: Witchcraft.Setoid.equivalent?(a, b)
end
#######
# Ord #
#######
definst Witchcraft.Ord, for: Algae.Either.Left do
custom_generator(_) do
1
|> TypeClass.Property.Generator.generate()
|> Left.new()
end
def compare(_, %Algae.Either.Right{}), do: :lesser
def compare(%Left{left: a}, %Left{left: b}), do: Witchcraft.Ord.compare(a, b)
end
definst Witchcraft.Ord, for: Algae.Either.Right do
custom_generator(_) do
1
|> TypeClass.Property.Generator.generate()
|> Right.new()
end
def compare(_, %Left{}), do: :greater
def compare(%Right{right: a}, %Right{right: b}), do: Witchcraft.Ord.compare(a, b)
end
#############
# Semigroup #
#############
definst Witchcraft.Semigroup, for: Algae.Either.Left do
custom_generator(_) do
1
|> TypeClass.Property.Generator.generate()
|> Left.new()
end
def append(left, %Right{}), do: left
def append(%Left{left: a}, %Left{left: b}), do: %Left{left: a <> b}
end
definst Witchcraft.Semigroup, for: Algae.Either.Right do
custom_generator(_) do
1
|> TypeClass.Property.Generator.generate()
|> Algae.Either.Right.new()
end
def append(_, left = %Left{}), do: left
def append(%Right{right: a}, %Right{right: b}), do: %Right{right: a <> b}
end
##########
# Monoid #
##########
definst Witchcraft.Monoid, for: Algae.Either.Left do
def empty(%Left{left: a}), do: %Right{right: Witchcraft.Monoid.empty(a)}
end
definst Witchcraft.Monoid, for: Algae.Either.Right do
def empty(%Right{right: a}), do: %Right{right: Witchcraft.Monoid.empty(a)}
end
# ###########
# # Functor #
# ###########
definst Witchcraft.Functor, for: Algae.Either.Left do
def map(left, _), do: left
end
definst Witchcraft.Functor, for: Algae.Either.Right do
def map(%Right{right: data}, fun), do: data |> fun.() |> Right.new()
end
# ############
# # Foldable #
# ############
definst Witchcraft.Foldable, for: Algae.Either.Left do
def right_fold(_, seed, _), do: seed
end
definst Witchcraft.Foldable, for: Algae.Either.Right do
def right_fold(%Right{right: inner}, seed, fun), do: fun.(inner, seed)
end
# ###############
# # Traversable #
# ###############
definst Witchcraft.Traversable, for: Algae.Either.Left do
@force_type_instance true
def traverse(left = %Left{left: value}, link) do
value
|> link.()
|> of(left)
end
end
definst Witchcraft.Traversable, for: Algae.Either.Right do
def traverse(%Right{right: value}, link), do: map(link.(value), &Right.new/1)
end
# #########
# # Apply #
# #########
definst Witchcraft.Apply, for: Algae.Either.Left do
def convey(left, _), do: left
end
definst Witchcraft.Apply, for: Algae.Either.Right do
def convey(_, left = %Left{}), do: left
def convey(data, %Right{right: fun}), do: map(data, fun)
end
###############
# Applicative #
###############
definst Witchcraft.Applicative, for: Algae.Either.Left do
@force_type_instance true
def of(_, data), do: Right.new(data)
end
definst Witchcraft.Applicative, for: Algae.Either.Right do
def of(_, data), do: Right.new(data)
end
# #########
# # Chain #
# #########
definst Witchcraft.Chain, for: Algae.Either.Left do
def chain(left, _), do: left
end
definst Witchcraft.Chain, for: Algae.Either.Right do
def chain(%Right{right: data}, link), do: link.(data)
end
# #########
# # Monad #
# #########
definst Witchcraft.Monad, for: Algae.Either.Left
definst Witchcraft.Monad, for: Algae.Either.Right
# ##########
# # Extend #
# ##########
definst Witchcraft.Extend, for: Algae.Either.Left do
def nest(_), do: Left.new()
end
definst Witchcraft.Extend, for: Algae.Either.Right do
def nest(inner), do: Right.new(inner)
end
================================================
FILE: lib/algae/free.ex
================================================
defmodule Algae.Free do
@moduledoc """
A "free" structure that converts functors into monads by embedding them in
a special structure with all of the monadic heavy lifting done for you.
Similar to trees and lists, but with the ability to add a struct "tag",
at each level. Often used for DSLs, interpreters, or building structured data.
For a simple introduction to the "free monad + interpreter" pattern, we recommend
[Why free monads matter](http://www.haskellforall.com/2012/06/you-could-have-invented-free-monads.html).
## Anatomy
### Pure
`Pure` simply holds a plain value.
%Free.Pure{pure: 42}
### Roll
`Roll` resursively containment of more `Free` structures embedded in
a another ADT. For example, with `Id`:
%Free.Roll{
roll: %Id{
id: %Pure{
pure: 42
}
}
}
"""
alias __MODULE__
alias Algae.Free.{Pure, Roll}
import Algae
use Witchcraft
defsum do
defdata(Roll :: any())
defdata(Pure :: any() \\ %Witchcraft.Unit{})
end
@doc """
Create an `Algae.Free.Pure` wrapping a single, simple value
## Examples
iex> new(42)
%Algae.Free.Pure{pure: 42}
"""
@spec new(any()) :: t()
def new(value), do: %Pure{pure: value}
@doc """
Add another layer to a free structure
## Examples
iex> 13
...> |> new()
...> |> layer(%Algae.Id{})
%Algae.Free.Roll{
roll: %Algae.Id{
id: %Algae.Free.Pure{
pure: 13
}
}
}
"""
@spec layer(t(), any()) :: t()
def layer(free, mutual), do: %Roll{roll: of(mutual, free)}
@doc """
Wrap a functor in a free structure.
## Examples
iex> wrap(%Algae.Id{id: 42})
%Algae.Free.Roll{
roll: %Algae.Id{
id: 42
}
}
"""
@spec wrap(Witchcraft.Functor.t()) :: Roll.t()
def wrap(functor), do: %Roll{roll: functor}
@doc """
Lift a plain functor up into a free monad.
## Examples
iex> free(%Algae.Id{id: 42})
%Algae.Free.Roll{
roll: %Algae.Id{
id: %Algae.Free.Pure{
pure: 42
}
}
}
"""
@spec free(Witchcraft.Functor.t()) :: t()
def free(functor) do
functor
|> map(&of(%Roll{}, &1))
|> wrap()
end
end
alias Algae.Free
alias Algae.Free.{Pure, Roll}
alias TypeClass.Property.Generator
alias Witchcraft.{Apply, Chain, Functor, Ord, Setoid}
import TypeClass
use Witchcraft
#############
# Generator #
#############
defimpl TypeClass.Property.Generator, for: Algae.Free.Pure do
def generate(_) do
[1, 1.1, "", []]
|> Enum.random()
|> Generator.generate()
|> Pure.new()
end
end
defimpl TypeClass.Property.Generator, for: Algae.Free.Roll do
def generate(_) do
inner = Algae.Id.new()
seed =
[1, 1.1, "", []]
|> Enum.random()
|> Generator.generate()
seed
|> Free.new()
|> Free.layer(inner)
|> Free.layer(inner)
end
end
##########
# Setoid #
##########
definst Witchcraft.Setoid, for: Algae.Free.Pure do
custom_generator(_) do
1
|> Generator.generate()
|> Pure.new()
end
def equivalent?(_, %Roll{}), do: false
def equivalent?(%Pure{pure: a}, %Pure{pure: b}), do: Setoid.equivalent?(a, b)
end
definst Witchcraft.Setoid, for: Algae.Free.Roll do
custom_generator(_) do
inner = Algae.Id.new()
seed = Generator.generate(1)
seed
|> Free.new()
|> Free.layer(inner)
|> Free.layer(inner)
end
def equivalent?(_, %Pure{}), do: false
def equivalent?(%Roll{roll: a}, %Roll{roll: b}), do: Setoid.equivalent?(a, b)
end
#######
# Ord #
#######
definst Witchcraft.Ord, for: Algae.Free.Pure do
custom_generator(_) do
1
|> TypeClass.Property.Generator.generate()
|> Free.new()
end
def compare(_, %Roll{}), do: :lesser
def compare(%Pure{pure: a}, %Pure{pure: b}), do: Ord.compare(a, b)
end
definst Witchcraft.Ord, for: Algae.Free.Roll do
custom_generator(_) do
inner = Algae.Id.new()
seed = Generator.generate(1)
seed
|> Free.new()
|> Free.layer(inner)
|> Free.layer(inner)
end
def compare(%Roll{}, %Pure{}), do: :greater
def compare(%Roll{roll: a}, %Roll{roll: b}), do: Ord.compare(a, b)
end
###########
# Functor #
###########
definst Witchcraft.Functor, for: Algae.Free.Pure do
def map(%Pure{pure: data}, fun), do: %Pure{pure: fun.(data)}
end
definst Witchcraft.Functor, for: Algae.Free.Roll do
def map(%Roll{roll: data}, fun) do
data
|> Functor.map(&Functor.map(&1, fun))
|> Roll.new()
end
end
#########
# Apply #
#########
definst Witchcraft.Apply, for: Algae.Free.Pure do
def convey(%Pure{pure: data}, %Pure{pure: fun}), do: %Pure{pure: fun.(data)}
def convey(pure, %Roll{roll: rolled}) do
rolled
|> Functor.map(&Apply.convey(pure, &1))
|> Roll.new()
end
end
definst Witchcraft.Apply, for: Algae.Free.Roll do
def convey(%Roll{roll: rolled}, %Pure{pure: fun}) do
rolled
|> Functor.map(&Functor.map(&1, fun))
|> Roll.new()
end
def convey(roll, %Roll{roll: rolled}) do
rolled
|> Functor.map(&Apply.convey(roll, &1))
|> Roll.new()
end
end
###############
# Applicative #
###############
definst Witchcraft.Applicative, for: Algae.Free.Pure do
def of(_, value), do: %Pure{pure: value}
end
definst Witchcraft.Applicative, for: Algae.Free.Roll do
def of(_, value), do: %Pure{pure: value}
end
#########
# Chain #
#########
definst Witchcraft.Chain, for: Algae.Free.Pure do
def chain(%Pure{pure: pure}, link), do: link.(pure)
end
definst Witchcraft.Chain, for: Algae.Free.Roll do
def chain(%Roll{roll: rolled}, link) do
rolled
|> Functor.map(&Chain.chain(&1, link))
|> Roll.new()
end
end
#########
# Monad #
#########
definst(Witchcraft.Monad, for: Algae.Free.Pure)
definst(Witchcraft.Monad, for: Algae.Free.Roll)
================================================
FILE: lib/algae/id/applicative.ex
================================================
import TypeClass
definst Witchcraft.Applicative, for: Algae.Id do
def of(_, data), do: Algae.Id.new(data)
end
================================================
FILE: lib/algae/id/apply.ex
================================================
import TypeClass
use Witchcraft
definst Witchcraft.Apply, for: Algae.Id do
def convey(data, %{id: fun}), do: map(data, fun)
end
================================================
FILE: lib/algae/id/chain.ex
================================================
import TypeClass
definst Witchcraft.Chain, for: Algae.Id do
def chain(%{id: data}, link), do: link.(data)
end
================================================
FILE: lib/algae/id/comonad.ex
================================================
import TypeClass
definst Witchcraft.Comonad, for: Algae.Id do
def extract(%{id: inner}), do: inner
end
================================================
FILE: lib/algae/id/extend.ex
================================================
import TypeClass
definst Witchcraft.Extend, for: Algae.Id do
def nest(inner), do: Algae.Id.new(inner)
end
================================================
FILE: lib/algae/id/foldable.ex
================================================
import TypeClass
definst Witchcraft.Foldable, for: Algae.Id do
def right_fold(%{id: data}, seed, fun), do: fun.(data, seed)
end
================================================
FILE: lib/algae/id/functor.ex
================================================
import TypeClass
definst Witchcraft.Functor, for: Algae.Id do
def map(%{id: data}, fun), do: data |> fun.() |> Algae.Id.new()
end
================================================
FILE: lib/algae/id/generator.ex
================================================
defimpl TypeClass.Property.Generator, for: Algae.Id do
def generate(_) do
[1, 1.1, "", []]
|> Enum.random()
|> TypeClass.Property.Generator.generate()
|> Algae.Id.new()
end
end
================================================
FILE: lib/algae/id/monad.ex
================================================
import TypeClass
definst Witchcraft.Monad, for: Algae.Id
================================================
FILE: lib/algae/id/monoid.ex
================================================
import TypeClass
definst Witchcraft.Monoid, for: Algae.Id do
def empty(%{id: sample}), do: sample |> Witchcraft.Monoid.empty() |> Algae.Id.new()
end
================================================
FILE: lib/algae/id/ord.ex
================================================
import TypeClass
use Witchcraft
definst Witchcraft.Ord, for: Algae.Id do
custom_generator(_) do
1
|> TypeClass.Property.Generator.generate()
|> Algae.Id.new()
end
def compare(%{id: a}, %{id: b}), do: Witchcraft.Ord.compare(a, b)
end
================================================
FILE: lib/algae/id/semigroup.ex
================================================
import TypeClass
use Witchcraft
definst Witchcraft.Semigroup, for: Algae.Id do
custom_generator(_) do
1
|> TypeClass.Property.Generator.generate()
|> Algae.Id.new()
end
def append(%{id: a}, %{id: b}), do: %Algae.Id{id: a <> b}
end
================================================
FILE: lib/algae/id/setoid.ex
================================================
import TypeClass
use Witchcraft
definst Witchcraft.Setoid, for: Algae.Id do
def equivalent?(%{id: a}, %{id: b}), do: a == b
end
================================================
FILE: lib/algae/id/traversable.ex
================================================
import TypeClass
use Witchcraft
definst Witchcraft.Traversable, for: Algae.Id do
def traverse(%{id: data}, link) do
data
|> link.()
|> map(&Algae.Id.new/1)
end
end
================================================
FILE: lib/algae/id.ex
================================================
defmodule Algae.Id do
@moduledoc ~S"""
The simplest ADT: a simple wrapper for some data
## Examples
iex> %Algae.Id{id: "hi!"}
%Algae.Id{id: "hi!"}
"""
import Algae
defdata any()
@doc """
Wrap some data in an `Algae.Id` wrapper
## Examples
iex> new(42)
%Algae.Id{id: 42}
"""
@spec new(any()) :: t()
def new(inner), do: %Algae.Id{id: inner}
end
================================================
FILE: lib/algae/internal/needs_explicit_default_error.ex
================================================
defmodule Algae.Internal.NeedsExplicitDefaultError do
defexception message: "Needs explicit default value"
end
================================================
FILE: lib/algae/internal.ex
================================================
defmodule Algae.Internal do
@moduledoc false
@type ast() :: {atom(), any(), any()}
@doc """
Construct a data type AST
"""
@spec data_ast(module(), Macro.Env.t() | [module()], ast()) :: ast()
def data_ast(lines, %{aliases: _} = caller) when is_list(lines) do
{field_values, field_types, specs, args, defaults} = module_elements(lines, caller)
arg_count = Enum.count(args)
overridables =
Enum.map(0..arg_count, &({:new_partial, &1}))
++ [new: arg_count]
# More verbose, but clearer.
# for arity <- 0..Enum.count(args) do
# {:new, arity}
# end
args_without_defaults =
Enum.map(args, fn({:\\, [], [stripped, _]}) -> stripped end)
quote do
use Quark
@type t :: %__MODULE__{unquote_splicing(field_types)}
defstruct unquote(field_values)
defpartial new_partial(unquote_splicing(args_without_defaults)) do
struct(__MODULE__, unquote(defaults))
end
@doc "Positional constructor, with args in the same order as they were defined in"
@spec new(unquote_splicing(specs)) :: t()
def new(unquote_splicing(args)) do
struct(__MODULE__, unquote(defaults))
end
defoverridable unquote(overridables)
end
end
def data_ast(modules, {:none, _, _}) do
full_module = modules |> List.wrap() |> Module.concat()
quote do
defmodule unquote(full_module) do
@type t :: %__MODULE__{}
defstruct []
@doc "Default #{__MODULE__} struct"
@spec new() :: t()
def new, do: struct(__MODULE__)
defoverridable [new: 0]
end
end
end
def data_ast(caller_module, type) do
default = default_value(type)
field = module_to_field(caller_module)
quote do
@type t :: %unquote(caller_module){
unquote(field) => unquote(type)
}
defstruct [{unquote(field), unquote(default)}]
@doc "Default #{__MODULE__} struct"
@spec new() :: t()
def new, do: struct(__MODULE__)
@doc "Constructor helper for piping"
@spec new(unquote(type)) :: t()
def new(field), do: struct(__MODULE__, [unquote(field), field])
defoverridable [new: 0, new: 1]
end
end
@spec data_ast([module()], any(), ast()) :: ast()
def data_ast(name, default, type_ctx) do
full_module = Module.concat(name)
field = module_to_field(name)
quote do
defmodule unquote(full_module) do
@type t :: %unquote(full_module){
unquote(field) => unquote(type_ctx)
}
defstruct [{unquote(field), unquote(default)}]
@doc "Default #{__MODULE__} struct. Value defaults to #{inspect unquote(default)}."
@spec new() :: t()
def new, do: struct(__MODULE__)
@doc "Helper for initializing struct with a specific value"
@spec new(unquote(type_ctx)) :: t()
def new(value), do: struct(__MODULE__, [{unquote(field), value}])
end
end
end
@spec embedded_data_ast() :: ast()
def embedded_data_ast do
quote do
@type t :: %__MODULE__{}
defstruct []
@doc "Default #{__MODULE__} struct"
@spec new() :: t()
def new, do: struct(__MODULE__)
end
end
def embedded_data_ast(module_ctx, default, type_ctx) do
field = module_to_field(module_ctx)
quote do
@type t :: %__MODULE__{
unquote(field) => unquote(type_ctx)
}
defstruct [{unquote(field), unquote(default)}]
@doc "Default #{__MODULE__} struct"
@spec new(unquote(type_ctx)) :: t()
def new(field \\ unquote(default)), do: struct(__MODULE__, [field])
defoverridable [new: 1]
end
end
@type field :: {atom(), [any()], [any()]}
@type type :: {atom(), [any()], [any()]}
@spec module_elements([ast()], Macro.Env.t())
:: {
[{field(), any()}],
[{field(), type()}],
[type],
[{:\\, [], any()}],
[{field(), any()}]
}
def module_elements(lines, caller) do
List.foldr(lines, {[], [], [], [], []},
fn(line, {value_acc, type_acc, typespec_acc, acc_arg, acc_mapping}) ->
{field, type, default_value} = normalize_elements(line, caller)
arg = {field, [], Elixir}
{
[{field, default_value} | value_acc],
[{field, type} | type_acc],
[type | typespec_acc],
[{:\\, [], [arg, default_value]} | acc_arg],
[{field, arg} | acc_mapping]
}
end)
end
@spec normalize_elements(ast(), Macro.Env.t()) :: {atom(), type(), any()}
def normalize_elements({:::, _, [{field, _, _}, type]}, caller) do
expanded_type = resolve_alias(type, caller)
{field, expanded_type, default_value(expanded_type)}
end
def normalize_elements({:\\, _, [{:::, _, [{field, _, _}, type]}, default]}, _) do
{field, type, default}
end
@spec resolve_alias(ast(), Macro.Env.t()) :: ast()
def resolve_alias({{_, _, _} = a, b, c}, caller) do
{resolve_alias(a, caller), b, c}
end
def resolve_alias({:. = a, b, [{:__aliases__, _, _} = the_alias | rest]}, caller) do
resolved_alias = Macro.expand(the_alias, caller)
{a, b, [resolved_alias | rest]}
end
def resolve_alias(a, _), do: a
@spec or_types([ast()], module()) :: [ast()]
def or_types({:\\, _, [{:::, _, [_, types]}, _]}, module_ctx) do
or_types(types, module_ctx)
end
def or_types([head | tail], module_ctx) do
Enum.reduce(tail, call_type(head, module_ctx), fn(module, acc) ->
{:|, [], [call_type(module, module_ctx), acc]}
end)
end
@spec modules(module(), [module()]) :: [module()]
def modules(top, module_ctx), do: [top | extract_name(module_ctx)]
@spec call_type(module(), [module()]) :: ast()
def call_type(new_module, module_ctx) do
full_module = List.wrap(module_ctx) ++ submodule_name(new_module)
{{:., [], [{:__aliases__, [alias: false], full_module}, :t]}, [], []}
end
@spec submodule_name({:defdata, any(), [{:::, any(), [any()]}]})
:: [module()]
def submodule_name({:defdata, _, [{:::, _, [body, _]}]}) do
body
|> case do
{:\\, _, [inner_module_ctx, _]} -> inner_module_ctx
{:__aliases__, _, module} -> module
outer_module_ctx -> outer_module_ctx
end
|> List.wrap()
end
def submodule_name({:defdata, _, [{:\\, _, [{:::, _, [{:__aliases__, _, module}, _]}, _]}]}) do
List.wrap(module)
end
def submodule_name({:defdata, _, [{:__aliases__, _, module}, _]}) do
List.wrap(module)
end
@spec extract_name({any(), any(), atom()} | [module()]) :: [module()]
def extract_name({_, _, inner_name}), do: List.wrap(inner_name)
def extract_name(module_chain) when is_list(module_chain), do: module_chain
def module_to_field(modules) when is_list(modules) do
modules
|> List.last()
|> module_to_field()
end
def module_to_field(module) do
module
|> Atom.to_string()
|> String.split(".")
|> List.last()
|> String.downcase()
|> String.trim_leading("elixir.")
|> String.to_atom()
end
# credo:disable-for-lines:21 Credo.Check.Refactor.CyclomaticComplexity
def default_value({{:., _, [{_, _, [:String]}, :t]}, _, _}), do: ""
def default_value({{:., _, [String, :t]}, _, _}), do: ""
def default_value({{:., _, [{_, _, adt}, :t]}, _, []}) do
quote do: unquote(Module.concat(adt)).new()
end
def default_value({{:., _, [module, :t]}, _, []}) do
quote do: unquote(module).new()
end
def default_value([_]), do: []
def default_value({type, _, _}) do
type
|> case do
:boolean -> false
:number -> 0
:integer -> 0
:float -> 0.0
:pos_integer -> 1
:non_neg_integer -> 0
:bitstring -> ""
:charlist -> []
[] -> []
:list -> []
:map -> %{}
:fun -> &Quark.id/1
:-> -> &Quark.id/1
:any -> nil
:t -> raise %Algae.Internal.NeedsExplicitDefaultError{message: "Type is lone `t`"}
atom -> atom
end
|> Macro.escape()
end
end
================================================
FILE: lib/algae/maybe.ex
================================================
defmodule Algae.Maybe do
@moduledoc ~S"""
The sum of `Algae.Maybe.Just` and `Algae.Maybe.Nothing`.
Maybe represents the presence or absence of something.
Please note that `nil` is actually a value, as it can be passed to functions!
`nil` is not bottom!
## Examples
iex> [1,2,3]
...> |> List.first()
...> |> case do
...> nil -> new()
...> head -> new(head)
...> end
%Algae.Maybe.Just{just: 1}
iex> []
...> |> List.first()
...> |> case do
...> nil -> new()
...> head -> new(head)
...> end
%Algae.Maybe.Nothing{}
"""
import Algae
alias Algae.Maybe.{Just, Nothing}
defsum do
defdata Nothing :: none()
defdata Just :: any()
end
@doc ~S"""
Put no value into the `Maybe` context (ie: make it a `Nothing`)
## Examples
iex> new()
%Algae.Maybe.Nothing{}
"""
@spec new() :: Nothing.t()
defdelegate new, to: Nothing, as: :new
@doc ~S"""
Put a value into the `Maybe` context (ie: make it a `Just`)
## Examples
iex> new(9)
%Algae.Maybe.Just{just: 9}
iex> new(nil)
%Algae.Maybe.Just{just: nil}
iex> new(nil, nothing: nil)
%Algae.Maybe.Nothing{}
iex> new(9, nothing: 9)
%Algae.Maybe.Nothing{}
iex> new(9, nothing: 1)
%Algae.Maybe.Just{just: 9}
"""
@spec new(any(), [nothing: any()]) :: Just.t() | Nothing.t()
def new(nothing_value, [nothing: nothing_value]), do: Nothing.new()
def new(value, _), do: Just.new(value)
@spec new(any()) :: Just.t()
def new(value), do: Just.new(value)
@doc """
Alias for `new(value, nothing: nil)`.
## Examples
iex> from_nillable(9)
%Algae.Maybe.Just{just: 9}
iex> from_nillable(nil)
%Algae.Maybe.Nothing{}
"""
@spec from_nillable(any()) :: Just.t()
def from_nillable(value), do: new(value, nothing: nil)
@doc """
Extract a value from a `Maybe`, falling back to a set value in the `Nothing` case.
## Examples
iex> from_maybe(%Algae.Maybe.Nothing{}, else: 42)
42
iex> %Algae.Maybe.Just{just: 1955} |> from_maybe(else: 42)
1955
"""
@spec from_maybe(t(), any()) :: any()
def from_maybe(%Nothing{}, [else: fallback]), do: fallback
def from_maybe(%Just{just: inner}, _), do: inner
end
alias Algae.Maybe.{Just, Nothing}
import TypeClass
use Witchcraft
#############
# Generator #
#############
defimpl TypeClass.Property.Generator, for: Algae.Maybe.Nothing do
def generate(_), do: Nothing.new()
end
defimpl TypeClass.Property.Generator, for: Algae.Maybe.Just do
def generate(_) do
[1, 1.1, "", []]
|> Enum.random()
|> TypeClass.Property.Generator.generate()
|> Just.new()
end
end
##########
# Setoid #
##########
definst Witchcraft.Setoid, for: Algae.Maybe.Nothing do
def equivalent?(_, %Nothing{}), do: true
def equivalent?(_, %Just{}), do: false
end
definst Witchcraft.Setoid, for: Algae.Maybe.Just do
def equivalent?(%Just{just: a}, %Just{just: b}), do: Witchcraft.Setoid.equivalent?(a, b)
def equivalent?(%Just{}, %Nothing{}), do: false
end
#######
# Ord #
#######
definst Witchcraft.Ord, for: Algae.Maybe.Nothing do
def compare(_, %Nothing{}), do: :equal
def compare(_, %Just{}), do: :lesser
end
definst Witchcraft.Ord, for: Algae.Maybe.Just do
custom_generator(_) do
1
|> TypeClass.Property.Generator.generate()
|> Just.new()
end
def compare(%Just{just: a}, %Just{just: b}), do: Witchcraft.Ord.compare(a, b)
def compare(%Just{}, %Nothing{}), do: :greater
end
#############
# Semigroup #
#############
definst Witchcraft.Semigroup, for: Algae.Maybe.Nothing do
def append(_, right), do: right
end
definst Witchcraft.Semigroup, for: Algae.Maybe.Just do
custom_generator(_) do
1
|> TypeClass.Property.Generator.generate()
|> Just.new()
end
def append(%Just{just: a}, %Just{just: b}), do: %Just{just: a <> b}
def append(just, %Nothing{}), do: just
end
##########
# Monoid #
##########
definst Witchcraft.Monoid, for: Algae.Maybe.Nothing do
def empty(nothing), do: nothing
end
definst Witchcraft.Monoid, for: Algae.Maybe.Just do
def empty(_), do: %Algae.Maybe.Nothing{}
end
###########
# Functor #
###########
definst Witchcraft.Functor, for: Algae.Maybe.Nothing do
def map(_, _), do: %Algae.Maybe.Nothing{}
end
definst Witchcraft.Functor, for: Algae.Maybe.Just do
def map(%{just: data}, fun), do: data |> fun.() |> Algae.Maybe.Just.new()
end
############
# Foldable #
############
definst Witchcraft.Foldable, for: Algae.Maybe.Nothing do
def right_fold(_, seed, _), do: seed
end
definst Witchcraft.Foldable, for: Algae.Maybe.Just do
def right_fold(%Just{just: inner}, seed, fun), do: fun.(inner, seed)
end
###############
# Traversable #
###############
# Not traversable because we don't have enough type information for Nothing
#########
# Apply #
#########
definst Witchcraft.Apply, for: Algae.Maybe.Nothing do
def convey(_, _), do: %Algae.Maybe.Nothing{}
end
definst Witchcraft.Apply, for: Algae.Maybe.Just do
alias Algae.Maybe.{Just, Nothing}
def convey(data, %Nothing{}), do: %Nothing{}
def convey(data, %Just{just: fun}), do: map(data, fun)
end
###############
# Applicative #
###############
definst Witchcraft.Applicative, for: Algae.Maybe.Nothing do
def of(_, data), do: Just.new(data)
end
definst Witchcraft.Applicative, for: Algae.Maybe.Just do
def of(_, data), do: Just.new(data)
end
#########
# Chain #
#########
definst Witchcraft.Chain, for: Algae.Maybe.Nothing do
def chain(_, _), do: %Nothing{}
end
definst Witchcraft.Chain, for: Algae.Maybe.Just do
def chain(%{just: data}, link), do: link.(data)
end
#########
# Monad #
#########
definst Witchcraft.Monad, for: Algae.Maybe.Nothing
definst Witchcraft.Monad, for: Algae.Maybe.Just
##########
# Extend #
##########
definst Witchcraft.Extend, for: Algae.Maybe.Nothing do
def nest(_), do: %Nothing{}
end
definst Witchcraft.Extend, for: Algae.Maybe.Just do
def nest(inner), do: Just.new(inner)
end
================================================
FILE: lib/algae/reader/applicative.ex
================================================
alias Algae.Reader
import TypeClass
use Witchcraft
definst Witchcraft.Applicative, for: Algae.Reader do
@force_type_instance true
def of(_, value), do: Reader.new(fn _ -> value end)
end
================================================
FILE: lib/algae/reader/apply.ex
================================================
alias Algae.Reader
import TypeClass
use Quark
use Witchcraft
definst Witchcraft.Apply, for: Algae.Reader do
@force_type_instance true
def convey(%Reader{reader: fun_a}, %Reader{reader: fun_b}) do
Reader.new(fn e -> curry(fun_a).(e).(fun_b.(e)) end)
end
end
================================================
FILE: lib/algae/reader/chain.ex
================================================
import TypeClass
definst Witchcraft.Chain, for: Algae.Reader do
@force_type_instance true
alias Algae.Reader
def chain(reader, link) do
Reader.new(fn e ->
reader
|> Reader.run(e)
|> link.()
|> Reader.run(e)
end)
end
end
================================================
FILE: lib/algae/reader/functor.ex
================================================
alias Algae.Reader
import TypeClass
use Witchcraft
definst Witchcraft.Functor, for: Algae.Reader do
@force_type_instance true
def map(%Reader{reader: inner}, fun), do: Reader.new(fn e -> e |> inner.() |> fun.() end)
end
================================================
FILE: lib/algae/reader/generator.ex
================================================
defimpl TypeClass.Property.Generator, for: Algae.Reader do
def generate(_) do
fn -> nil end
|> TypeClass.Property.Generator.generate()
|> Algae.Reader.new()
end
end
================================================
FILE: lib/algae/reader/monad.ex
================================================
import TypeClass
definst Witchcraft.Monad, for: Algae.Reader do
@force_type_instance true
end
================================================
FILE: lib/algae/reader.ex
================================================
defmodule Algae.Reader do
@moduledoc ~S"""
`Algae.Reader` allows you to pass some readable context around through actions.
This is useful in a number of situations, but the most common case is to weave
access to environment variables monadically.
For an illustrated guide to `Reader`s,
see [Thee Useful Monads](http://adit.io/posts/2013-06-10-three-useful-monads.html#the-state-monad).
## Examples
iex> use Witchcraft
...>
iex> correct =
...> monad %Algae.Reader{} do
...> count <- ask &Map.get(&1, :count)
...> bindings <- ask()
...> return (count == map_size(bindings))
...> end
...>
iex> sample_bindings = %{count: 3, a: 1, b: 2}
iex> correct_count = run(correct, sample_bindings)
iex> "Correct count for #{inspect sample_bindings}? #{correct_count}"
"Correct count for %{a: 1, b: 2, count: 3}? true"
...>
iex> bad_bindings = %{count: 100, a: 1, b: 2}
iex> bad_count = run(correct, bad_bindings)
iex> "Correct count for #{inspect bad_bindings}? #{bad_count}"
"Correct count for %{a: 1, b: 2, count: 100}? false"
Example adapted from
[source](https://hackage.haskell.org/package/mtl-2.2.1/docs/Control-Monad-Reader.html)
"""
alias __MODULE__
import Algae
use Witchcraft
defdata fun()
@doc """
`Reader` constructor.
## Examples
iex> newbie = new(fn x -> x * 10 end)
...> newbie.reader.(10)
100
"""
@spec new(fun()) :: t()
def new(fun), do: %Reader{reader: fun}
@doc """
Run the reader function with some argument.
iex> reader = new(fn x -> x + 5 end)
...> run(reader, 42)
47
This is the opposite of `new/1`.
iex> fun = fn x -> x + 5 end
...> fun.(42) == fun |> new() |> run(42)
true
"""
@spec run(t(), any()) :: any()
def run(%Reader{reader: fun}, arg), do: fun.(arg)
@doc """
Get the wrapped environment. Especially useful in monadic do-notation.
## Examples
iex> run(ask(), 42)
42
iex> use Witchcraft
...>
...> example_fun =
...> fn x ->
...> monad %Algae.Reader{} do
...> e <- ask()
...> return {x, e}
...> end
...> end
...>
...> 42
...> |> example_fun.()
...> |> run(7)
{42, 7}
"""
@spec ask() :: t()
def ask, do: Reader.new(fn x -> x end)
@doc ~S"""
Similar to `new/1` and `ask/0`. Construct an `Algae.Reader`,
but apply a function to the constructed envoronment.
The pun here is that you're "asking" a function for something.
## Examples
iex> fn x -> x * 10 end
...> |> ask()
...> |> run(5)
50
iex> use Witchcraft
...>
...> foo =
...> fn words ->
...> monad %Algae.Reader{} do
...> loud <- ask &(&1 == String.upcase(&1))
...> return(words <> (if loud, do: "!", else: "."))
...> end
...> end
...>
...> "Hello" |> foo.() |> run("WORLD") # "WORLD" is the context being asked for
"Hello!"
"""
@spec ask((any() -> any())) :: t()
def ask(fun) do
monad %Reader{} do
e <- ask
return fun.(e)
end
end
@doc """
Locally composes a function into a `Reader`.
Often the idea is to temporarily adapt the `Reader` without continuing this
change in later `run`s.
## Examples
iex> ask()
...> |> local(fn word -> word <> "!" end)
...> |> local(&String.upcase/1)
...> |> run("o hai thar")
"O HAI THAR!"
"""
@spec local(t(), (any() -> any())) :: any()
def local(reader, fun) do
monad %Reader{} do
e <- ask
return run(reader, fun.(e))
end
end
end
================================================
FILE: lib/algae/state/applicative.ex
================================================
import TypeClass
definst Witchcraft.Applicative, for: Algae.State do
@force_type_instance true
def of(_, value), do: %Algae.State{runner: fn x -> {value, x} end}
end
================================================
FILE: lib/algae/state/apply.ex
================================================
alias Algae.State
import TypeClass
definst Witchcraft.Apply, for: Algae.State do
@force_type_instance true
def convey(%State{runner: state_g}, %State{runner: state_f}) do
fg =
fn(s) ->
{x, t} = state_f.(s)
{y, u} = state_g.(t)
{x.(y), u}
end
State.new(fn x -> fg.(x) end)
end
end
================================================
FILE: lib/algae/state/chain.ex
================================================
alias Algae.State
import TypeClass
definst Witchcraft.Chain, for: Algae.State do
@force_type_instance true
def chain(state, link) do
State.state(fn s ->
{x, z} = State.run(state, s)
State.run(link.(x), z)
end)
end
end
================================================
FILE: lib/algae/state/functor.ex
================================================
alias Algae.State
import TypeClass
definst Witchcraft.Functor, for: Algae.State do
@force_type_instance true
def map(%State{runner: inner}, fun) do
run_map = fn({a, b}, f) -> {f.(a), b} end
st_tuple =
fn(g, s) ->
g
|> State.new()
|> State.run(s)
end
State.new(fn x ->
inner
|> st_tuple.(x)
|> run_map.(fun)
end)
end
end
================================================
FILE: lib/algae/state/generator.ex
================================================
defimpl TypeClass.Property.Generator, for: Algae.State do
def generate(_) do
inner =
[0, 1.1, "", []]
|> Enum.random()
|> TypeClass.Property.Generator.generate()
Algae.State.new(fn x -> {inner, x} end)
end
end
================================================
FILE: lib/algae/state/monad.ex
================================================
import TypeClass
definst Witchcraft.Monad, for: Algae.State do
@force_type_instance true
end
================================================
FILE: lib/algae/state.ex
================================================
defmodule Algae.State do
@moduledoc ~S"""
`Algae.State` describes a wrapped function that can be used to pass around some
"hidden" pure state.
This has numerous applications, but the primary advantage is purity. The state
gets passed around with the value, and the monadic DSL helps it feel more
natural than passing everything around by hand.
In many ways, `Algae.State` is a generalization of `Algae.Reader` and `Algae.Writer`.
See [Thee Useful Monads](http://adit.io/posts/2013-06-10-three-useful-monads.html#the-state-monad)
a nice, illustrated guide to how these work and relate.
## Anatomy
# To pass in concrete values
↓
%Algae.State{runner: fn access -> {value, state} end}
↑ ↑
# "explicit" value position "hidden" state position
## Examples
iex> use Witchcraft
...>
...> %Algae.State{}
...> |> monad do
...> name <- get()
...> let result = "Hello, #{name}!"
...>
...> put result
...> modify &String.upcase/1
...>
...> return result
...> end
...> |> run("world")
{
"Hello, world!",
"HELLO, WORLD!"
}
iex> use Witchcraft
...>
...> pop = fn -> state(fn([x | xs]) -> {x, xs} end) end
...> pull = fn -> state(fn(list = [x | _]) -> {x, list} end) end
...> push = &state(fn(xs) -> {%Witchcraft.Unit{}, [&1 | xs]} end)
...>
...> %Algae.State{}
...> |> monad do
...> push.(["a"])
...> push.(["b"])
...> push.(["c"])
...> push.(["d"])
...> push.(["e"])
...>
...> z <- pop.()
...> y <- pop.()
...> x <- pop.()
...>
...> push.(x <> y <> z)
...> pull.()
...> end
...> |> evaluate([])
["c", "d", "e"]
"""
alias __MODULE__
alias Witchcraft.Unit
use Witchcraft
@type runner :: (any() -> {any(), any()})
@type t :: %State{runner: runner()}
defstruct [runner: &State.default/1]
@spec default(any()) :: {integer(), any()}
def default(s), do: {s, s}
@doc """
Construct a new `Algae.State` struct from a state runner in the form
`fn x -> {y, z} end`
## Examples
iex> new(fn x -> {x + 1, x} end).runner.(42)
{43, 42}
"""
@spec new(State.runner()) :: State.t()
def new(runner), do: %State{runner: runner}
@doc """
Alias for `new/1` that reads better when importing the module.
## Examples
iex> state(fn x -> {x + 1, x} end).runner.(42)
{43, 42}
"""
@spec state(State.runner()) :: State.t()
def state(runner), do: new(runner)
@doc """
Extract the runner from an `Algae.State`.
Can be used as a curried version of `run/2`.
## Examples
iex> inner = fn x -> {0, x} end
...>
...> run(%Algae.State{runner: inner}).(42) == inner.(42)
true
"""
@spec run(State.t()) :: State.runner()
def run(%State{runner: fun}), do: fun
@doc """
Run an `Algae.State` by passing in some initial state to actualy run the enclosed
state runner.
## Examples
iex> use Witchcraft
...>
...> %Algae.State{}
...> |> of(2)
...> |> run(0)
{2, 0}
"""
@spec run(State.t(), any()) :: any()
def run(%State{runner: fun}, arg), do: fun.(arg)
@doc """
Set the stateful position of an `Algae.Struct`.
Not unlike `Algae.Writer.tell/1`.
## Examples
iex> 1
...> |> put()
...> |> run(0)
{%Witchcraft.Unit{}, 1}
"""
@spec put(any()) :: State.t()
def put(s), do: State.new(fn _ -> {%Unit{}, s} end)
@doc ~S"""
Run a function over the "state" portion of the runner.
## Examples
iex> fn x -> x + 1 end
...> |> modify()
...> |> run(42)
{%Witchcraft.Unit{}, 43}
iex> use Witchcraft
...>
...> %Algae.State{}
...> |> monad do
...> name <- get()
...>
...> put "State"
...> modify &String.upcase/1
...>
...> return "Hello, #{name}!"
...> end
...> |> run("world")
{"Hello, world!", "STATE"}
"""
@spec modify((any() -> any())) :: State.t()
def modify(fun), do: State.new(fn s -> {%Unit{}, fun.(s)} end)
@doc """
Set both sides of an `Algae.State` struct.
## Examples
iex> run(get(), 1)
{1, 1}
"""
@spec get() :: State.t()
def get, do: State.new(fn a -> {a, a} end)
@doc """
Set both sides of an `Algae.State` struct, plus running a function over the
value portion of the inner state.
## Examples
iex> fn x -> x * 10 end
...> |> get()
...> |> run(4)
{40, 4}
"""
@spec get((any() -> any())) :: State.t()
def get(fun) do
monad %Algae.State{} do
s <- get()
return fun.(s)
end
end
@doc ~S"""
Run the enclosed `Algae.State` runner, and return the value (no state).
## Examples
iex> use Witchcraft
...>
...> %Algae.State{}
...> |> monad do
...> name <- get()
...> put "Ignored"
...> return "Hello, #{name}!"
...> end
...> |> evaluate("world")
"Hello, world!"
"""
@spec evaluate(State.t(), any()) :: any()
def evaluate(state, value) do
state
|> run(value)
|> elem(0)
end
@doc ~S"""
Run the enclosed `Algae.State` runner, and return the state (no value).
## Examples
iex> fn x -> x + 1 end
...> |> get()
...> |> execute(1)
1
iex> use Witchcraft
...>
...> %Algae.State{}
...> |> monad do
...> whatevs <- get()
...> put "State"
...> return "Hello, #{whatevs}!"
...> end
...> |> execute("world")
"State"
"""
@spec execute(State.t(), any()) :: any()
def execute(state, value) do
state
|> run(value)
|> elem(1)
end
end
================================================
FILE: lib/algae/tree/binary_search/applicative.ex
================================================
alias Algae.Tree.BinarySearch.Node
import TypeClass
use Witchcraft
definst Witchcraft.Applicative, for: Algae.Tree.BinarySearch.Empty do
def of(_, data), do: %Node{node: data}
end
definst Witchcraft.Applicative, for: Algae.Tree.BinarySearch.Node do
@force_type_instance true
def of(_, data), do: %Node{node: data}
end
================================================
FILE: lib/algae/tree/binary_search/apply.ex
================================================
alias Algae.Tree.BinarySearch.{Empty, Node}
import TypeClass
use Witchcraft
definst Witchcraft.Apply, for: Algae.Tree.BinarySearch.Empty do
def convey(_, _), do: %Empty{}
end
definst Witchcraft.Apply, for: Algae.Tree.BinarySearch.Node do
def convey(_, %Empty{}), do: %Empty{}
def convey(%{node: node, left: left, right: right}, tree_funs = %Node{node: fun}) do
%Node{
node: fun.(node),
left: Witchcraft.Apply.convey(left, tree_funs),
right: Witchcraft.Apply.convey(right, tree_funs)
}
end
end
================================================
FILE: lib/algae/tree/binary_search/chain.ex
================================================
alias Algae.Tree.BinarySearch.{Empty, Node}
import TypeClass
use Witchcraft
definst Witchcraft.Chain, for: Algae.Tree.BinarySearch.Empty do
def chain(_, _), do: %Empty{}
end
definst Witchcraft.Chain, for: Algae.Tree.BinarySearch.Node do
def chain(%Node{node: node}, link), do: link.(node)
end
================================================
FILE: lib/algae/tree/binary_search/extend.ex
================================================
alias Algae.Tree.BinarySearch.{Empty, Node}
import TypeClass
use Witchcraft
definst Witchcraft.Extend, for: Algae.Tree.BinarySearch.Empty do
def nest(_), do: %Empty{}
end
definst Witchcraft.Extend, for: Algae.Tree.BinarySearch.Node do
def nest(tree = %Node{left: left, right: right}) do
%Node{
node: tree,
left: Witchcraft.Extend.nest(left),
right: Witchcraft.Extend.nest(right)
}
end
end
================================================
FILE: lib/algae/tree/binary_search/foldable.ex
================================================
alias Algae.Tree.BinarySearch.Node
import TypeClass
use Witchcraft
definst Witchcraft.Foldable, for: Algae.Tree.BinarySearch.Empty do
def right_fold(_, seed, _), do: seed
end
definst Witchcraft.Foldable, for: Algae.Tree.BinarySearch.Node do
def right_fold(%Node{node: node, left: left, right: right}, seed, fun) do
folded_right = Witchcraft.Foldable.right_fold(right, seed, fun)
folded_left = Witchcraft.Foldable.right_fold(left, folded_right, fun)
fun.(node, folded_left)
end
end
================================================
FILE: lib/algae/tree/binary_search/functor.ex
================================================
alias Algae.Tree.BinarySearch.{Empty, Node}
alias Witchcraft.Functor
import TypeClass
definst Witchcraft.Functor, for: Algae.Tree.BinarySearch.Empty do
def map(_, _), do: %Empty{}
end
definst Witchcraft.Functor, for: Algae.Tree.BinarySearch.Node do
def map(%Node{node: node, left: left, right: right}, fun) do
%Node{
node: fun.(node),
left: Functor.map(left, fun),
right: Functor.map(right, fun)
}
end
end
================================================
FILE: lib/algae/tree/binary_search/generator.ex
================================================
alias Algae.Tree.BinarySearch.{Empty, Node}
use Witchcraft
defimpl TypeClass.Property.Generator, for: Algae.Tree.BinarySearch.Empty do
def generate(_), do: Empty.new()
end
defimpl TypeClass.Property.Generator, for: Algae.Tree.BinarySearch.Node do
def generate(_) do
random_node()
end
def random_node do
case Enum.random(Enum.to_list(0..5)) do
0 ->
%Node{node: random_value()}
1 ->
%Node{node: random_value()}
2 ->
%Node{
node: random_value(),
left: random_node(),
right: random_node()
}
_ ->
%Empty{}
end
end
def random_value do
[1, 1.1, "", []]
|> Enum.random()
|> TypeClass.Property.Generator.generate()
end
end
================================================
FILE: lib/algae/tree/binary_search/monad.ex
================================================
import TypeClass
use Witchcraft
definst(Witchcraft.Monad, for: Algae.Tree.BinarySearch.Empty)
definst Witchcraft.Monad, for: Algae.Tree.BinarySearch.Node do
@force_type_instance true
end
================================================
FILE: lib/algae/tree/binary_search/monoid.ex
================================================
alias Algae.Tree.BinarySearch, as: BST
alias Algae.Tree.BinarySearch.{Empty, Node}
import TypeClass
use Witchcraft
definst Witchcraft.Monoid, for: Algae.Tree.BinarySearch.Empty do
def empty(empty), do: empty
end
definst Witchcraft.Monoid, for: Algae.Tree.BinarySearch.Node do
def empty(_), do: %Empty{}
end
================================================
FILE: lib/algae/tree/binary_search/ord.ex
================================================
alias Algae.Tree.BinarySearch.{Empty, Node}
import TypeClass
use Witchcraft
definst Witchcraft.Ord, for: Algae.Tree.BinarySearch.Empty do
def compare(_, %Empty{}), do: :equal
def compare(_, %Node{}), do: :lesser
end
definst Witchcraft.Ord, for: Algae.Tree.BinarySearch.Node do
custom_generator(_) do
random_node()
end
def random_node do
Enum.random([
%Empty{},
%Empty{},
%Empty{},
%Node{
node: random_value()
},
%Node{
node: random_value(),
left: random_value(),
right: random_value()
}
])
end
def random_value, do: TypeClass.Property.Generator.generate(1)
def compare(%Node{}, %Empty{}), do: :greater
def compare(%Node{node: a}, %Node{node: b}), do: Witchcraft.Ord.compare(a, b)
end
================================================
FILE: lib/algae/tree/binary_search/semigroup.ex
================================================
alias Algae.Tree.BinarySearch, as: BST
alias Algae.Tree.BinarySearch.{Empty, Node}
import TypeClass
use Witchcraft
definst Witchcraft.Semigroup, for: Algae.Tree.BinarySearch.Empty do
def append(_, %Empty{}), do: %Empty{}
def append(_, node = %Node{}), do: node
end
definst Witchcraft.Semigroup, for: Algae.Tree.BinarySearch.Node do
def append(node, %Empty{}), do: node
def append(node_a, node_b) do
node_a
|> BST.to_list()
|> Enum.concat(BST.to_list(node_b))
|> BST.from_list()
end
end
================================================
FILE: lib/algae/tree/binary_search/setoid.ex
================================================
alias Algae.Tree.BinarySearch, as: BST
alias Algae.Tree.BinarySearch.{Empty, Node}
import TypeClass
use Witchcraft
definst Witchcraft.Setoid, for: Algae.Tree.BinarySearch.Empty do
def equivalent?(_, %Empty{}), do: true
def equivalent?(_, %Node{}), do: false
end
definst Witchcraft.Setoid, for: Algae.Tree.BinarySearch.Node do
def equivalent?(%Node{}, %Empty{}), do: false
def equivalent?(%Node{node: a}, %Node{node: b}) do
Witchcraft.Setoid.equivalent?(a, b)
end
end
================================================
FILE: lib/algae/tree/binary_search.ex
================================================
defmodule Algae.Tree.BinarySearch do
@moduledoc """
Represent a `BinarySearch` tree.
## Examples
iex> alias Algae.Tree.BinarySearch, as: BSTree
...>
...> BSTree.Node.new(
...> 42,
...> BSTree.Node.new(77),
...> BSTree.Node.new(
...> 1234,
...> BSTree.Node.new(98),
...> BSTree.Node.new(32)
...> )
...> )
%Algae.Tree.BinarySearch.Node{
node: 42,
left: %Algae.Tree.BinarySearch.Node{
node: 77,
left: %Algae.Tree.BinarySearch.Empty{},
right: %Algae.Tree.BinarySearch.Empty{}
},
right: %Algae.Tree.BinarySearch.Node{
node: 1234,
left: %Algae.Tree.BinarySearch.Node{
node: 98,
left: %Algae.Tree.BinarySearch.Empty{},
right: %Algae.Tree.BinarySearch.Empty{}
},
right: %Algae.Tree.BinarySearch.Node{
node: 32,
left: %Algae.Tree.BinarySearch.Empty{},
right: %Algae.Tree.BinarySearch.Empty{}
}
}
}
"""
alias __MODULE__
alias BinarySearch.{Empty, Node}
import Algae
use Witchcraft, except: [to_list: 1]
defsum do
defdata(Empty :: none())
defdata Node do
node :: any()
left :: BinarySearch.t() \\ BinarySearch.Empty.new()
right :: BinarySearch.t() \\ BinarySearch.Empty.new()
end
end
@doc """
Create an empty tree.
## Examples
iex> new()
%Algae.Tree.BinarySearch.Empty{}
"""
@spec new() :: Empty.t()
def new, do: %Empty{}
@doc """
Bring a value into an otherwise empty tree.
## Examples
iex> new(42)
%Algae.Tree.BinarySearch.Node{
node: 42,
left: %Algae.Tree.BinarySearch.Empty{},
right: %Algae.Tree.BinarySearch.Empty{}
}
"""
@spec new(any()) :: Node.t()
def new(value), do: %Node{node: value}
@doc """
Insert a new element into a tree.
## Examples
iex> insert(new(42), 43)
%Algae.Tree.BinarySearch.Node{
node: 42,
right: %Algae.Tree.BinarySearch.Node{
node: 43
}
}
"""
@spec insert(t(), any()) :: t()
def insert(%Empty{}, value), do: new(value)
def insert(tree = %Node{node: node, left: left, right: right}, orderable) do
case compare(orderable, node) do
:equal -> tree
:greater -> %{tree | right: insert(right, orderable)}
:lesser -> %{tree | left: insert(left, orderable)}
end
end
def insert(%Empty{}, value), do: new(value)
def insert(tree = %Node{node: node, left: left, right: right}, orderable) do
case compare(orderable, node) do
:equal -> tree
:greater -> %{tree | right: insert(right, orderable)}
:lesser -> %{tree | left: insert(left, orderable)}
end
end
@doc """
Remove an element from a tree by value.
## Examples
iex> alias Algae.Tree.BinarySearch, as: BSTree
...>
...> BSTree.Node.new(
...> 42,
...> BSTree.Node.new(77),
...> BSTree.Node.new(
...> 1234,
...> BSTree.Node.new(98),
...> BSTree.Node.new(32)
...> )
...> ) |> delete(98)
%Algae.Tree.BinarySearch.Node{
node: 42,
left: %Algae.Tree.BinarySearch.Node{
node: 77
},
right: %Algae.Tree.BinarySearch.Node{
node: 1234,
right: %Algae.Tree.BinarySearch.Node{
node: 32
}
}
}
"""
@spec delete(t(), any()) :: t()
def delete(%Empty{}, _), do: %Empty{}
def delete(tree = %Node{node: node, left: left, right: right}, orderable) do
case compare(orderable, node) do
:greater ->
%{tree | right: delete(right, orderable)}
:lesser ->
%{tree | left: delete(left, orderable)}
:equal ->
case tree do
%{left: %Empty{}} -> right
%{right: %Empty{}} -> left
%{right: %{node: shift}} -> %{tree | node: shift, right: delete(right, shift)}
end
end
end
@doc """
Flatten a tree into a list.
## Examples
iex> alias Algae.Tree.BinarySearch, as: BSTree
...>
...> BSTree.Node.new(
...> 42,
...> BSTree.Node.new(77),
...> BSTree.Node.new(
...> 1234,
...> BSTree.Node.new(98),
...> BSTree.Node.new(32)
...> )
...> )
...> |> BSTree.to_list()
[42, 77, 1234, 98, 32]
"""
@spec to_list(t()) :: list()
def to_list(tree), do: Witchcraft.Foldable.to_list(tree)
@doc """
Flatten a tree into a list with elements sorted.
## Examples
iex> alias Algae.Tree.BinarySearch, as: BSTree
...>
...> BSTree.Node.new(
...> 42,
...> BSTree.Node.new(77),
...> BSTree.Node.new(
...> 1234,
...> BSTree.Node.new(98),
...> BSTree.Node.new(32)
...> )
...> )
...> |> BSTree.to_ordered_list()
[32, 42, 77, 98, 1234]
"""
@spec to_ordered_list(t()) :: list()
def to_ordered_list(tree), do: tree |> to_list() |> Enum.sort()
@doc """
Build a `BinarySearch` tree from a list.
## Examples
iex> Algae.Tree.BinarySearch.from_list([42, 77, 1234, 98, 32])
%Algae.Tree.BinarySearch.Node{
node: 42,
left: %Algae.Tree.BinarySearch.Node{
node: 32
},
right: %Algae.Tree.BinarySearch.Node{
node: 77,
right: %Algae.Tree.BinarySearch.Node{
node: 1234,
left: %Algae.Tree.BinarySearch.Node{
node: 98
}
}
}
}
"""
@spec from_list(list()) :: t()
def from_list([]), do: %Empty{}
def from_list([head | tail]), do: from_list(tail, new(head))
@doc """
Build a `BinarySearch` tree from a list and attach to an existing tree.
## Examples
iex> Algae.Tree.BinarySearch.from_list([42, 77, 1234, 98, 32], new(-9))
%Algae.Tree.BinarySearch.Node{
node: -9,
right: %Algae.Tree.BinarySearch.Node{
left: %Algae.Tree.BinarySearch.Node{
node: 32
},
node: 42,
right: %Algae.Tree.BinarySearch.Node{
node: 77,
right: %Algae.Tree.BinarySearch.Node{
node: 1234,
left: %Algae.Tree.BinarySearch.Node{
node: 98
},
right: %Algae.Tree.BinarySearch.Empty{}
}
}
}
}
"""
@spec from_list(list(), t()) :: t()
def from_list([], seed), do: seed
def from_list([head | tail], seed), do: from_list(tail, insert(seed, head))
end
================================================
FILE: lib/algae/tree/rose/applicative.ex
================================================
import TypeClass
definst Witchcraft.Applicative, for: Algae.Tree.Rose do
def of(_, value), do: Algae.Tree.Rose.new(value)
end
================================================
FILE: lib/algae/tree/rose/apply.ex
================================================
alias Algae.Tree.Rose
alias Witchcraft.{Apply, Functor}
import TypeClass
definst Witchcraft.Apply, for: Algae.Tree.Rose do
def convey(tree = %Rose{rose: rose, forest: forest}, %Rose{rose: fun, forest: funs}) do
new_forest =
Functor.map(forest, &Functor.map(&1, fun))
++ Functor.map(funs, &Apply.convey(tree, &1))
%Rose{
rose: fun.(rose),
forest: new_forest
}
end
end
================================================
FILE: lib/algae/tree/rose/chain.ex
================================================
alias Algae.Tree.Rose
alias Witchcraft.{Chain, Functor}
import TypeClass
definst Witchcraft.Chain, for: Algae.Tree.Rose do
def chain(%Rose{rose: rose, forest: forest}, link) do
%Rose{rose: new_rose, forest: mid_forest} = link.(rose)
new_forest = mid_forest ++ Functor.map(forest, &Chain.chain(&1, link))
Rose.new(new_rose, new_forest)
end
end
================================================
FILE: lib/algae/tree/rose/foldable.ex
================================================
alias Algae.Tree.Rose
alias Witchcraft.Foldable
import TypeClass
definst Witchcraft.Foldable, for: Algae.Tree.Rose do
def right_fold(%Rose{rose: rose, forest: forest}, acc, fun) do
fun.(rose, Foldable.right_fold(forest, acc, fun))
end
end
================================================
FILE: lib/algae/tree/rose/functor.ex
================================================
alias Algae.Tree.Rose
alias Witchcraft.Functor
import TypeClass
definst Witchcraft.Functor, for: Algae.Tree.Rose do
def map(%Rose{rose: rose, forest: forest}, fun) do
%Rose{
rose: fun.(rose),
forest: Functor.map(forest, &Functor.map(&1, fun))
}
end
end
================================================
FILE: lib/algae/tree/rose/generator.ex
================================================
alias Algae.Tree.Rose
alias TypeClass.Property.Generator
defimpl TypeClass.Property.Generator, for: Algae.Tree.Rose do
def generate(_) do
case Enum.random(0..2) do
0 -> Rose.new(rose(), forest())
_ -> Rose.new(rose())
end
end
def forest do
fn ->
case Enum.random(0..10) do
0 -> Rose.new(rose(), forest())
_ -> Rose.new(rose())
end
end
|> Stream.repeatedly()
|> Enum.take(Enum.random(0..5))
end
def rose do
[1, 1.1, "", []]
|> Enum.random()
|> Generator.generate()
end
end
================================================
FILE: lib/algae/tree/rose/monad.ex
================================================
import TypeClass
definst Witchcraft.Monad, for: Algae.Tree.Rose
================================================
FILE: lib/algae/tree/rose.ex
================================================
defmodule Algae.Tree.Rose do
@moduledoc """
A tree with any number of nodes at each level
## Examples
%Algae.Tree.Rose{
rose: 42,
forest: [
%Algae.Tree.Rose{
rose: "hi"
},
%Algae.Tree.Rose{
forest: [
%Algae.Tree.Rose{
rose: 0.4
}
]
},
%Algae.Tree.Rose{
rose: "there"
}
]
}
"""
alias __MODULE__
import Algae
@type rose :: any()
@type forest :: [t()]
defdata do
rose :: any()
forest :: [t()]
end
@doc """
Create a simple `Algae.Rose` tree, with an empty forest and one rose.
## Examples
iex> new(42)
%Algae.Tree.Rose{
rose: 42,
forest: []
}
"""
@spec new(rose()) :: t()
def new(rose), do: %Rose{rose: rose, forest: []}
@doc """
Create an `Algae.Rose` tree, passing a forest and a rose.
## Examples
iex> new(42, [new(55), new(14)])
%Algae.Tree.Rose{
rose: 42,
forest: [
%Algae.Tree.Rose{rose: 55},
%Algae.Tree.Rose{rose: 14}
]
}
"""
@spec new(rose(), forest()) :: t()
def new(rose, forest), do: %Rose{rose: rose, forest: forest}
@doc """
Wrap another tree around an existing one, relegating it to the forest.
## Examples
iex> 55
...> |> new()
...> |> layer(42)
...> |> layer(99)
...> |> layer(6)
%Algae.Tree.Rose{
rose: 6,
forest: [
%Algae.Tree.Rose{
rose: 99,
forest: [
%Algae.Tree.Rose{
rose: 42,
forest: [
%Algae.Tree.Rose{
rose: 55
}
]
}
]
}
]
}
"""
@spec layer(t(), rose()) :: t()
def layer(tree, rose), do: %Rose{rose: rose, forest: [tree]}
end
================================================
FILE: lib/algae/writer/applicative.ex
================================================
alias Algae.Writer
import TypeClass
use Witchcraft
definst Witchcraft.Applicative, for: Algae.Writer do
def of(%Writer{writer: {_, log}}, value), do: Writer.new(value, empty(log))
end
================================================
FILE: lib/algae/writer/apply.ex
================================================
alias Algae.Writer
import TypeClass
use Quark
use Witchcraft
definst Witchcraft.Apply, for: Algae.Writer do
def convey(%Writer{writer: {value, log_a}}, %Writer{writer: {fun, log_b}}) do
Writer.new(fun.(value), log_b <> log_a)
end
end
================================================
FILE: lib/algae/writer/chain.ex
================================================
alias Algae.Writer
import TypeClass
use Witchcraft
definst Witchcraft.Chain, for: Algae.Writer do
def chain(%Writer{writer: {old_value, old_log}}, link) do
%Writer{writer: {new_value, new_log}} = link.(old_value)
Writer.new(new_value, old_log <> new_log)
end
end
================================================
FILE: lib/algae/writer/functor.ex
================================================
alias Algae.Writer
import TypeClass
use Witchcraft
definst Witchcraft.Functor, for: Algae.Writer do
def map(%Writer{writer: {value, log}}, fun), do: Writer.new(fun.(value), log)
end
================================================
FILE: lib/algae/writer/generator.ex
================================================
alias TypeClass.Property.Generator
defimpl TypeClass.Property.Generator, for: Algae.Writer do
def generate(_), do: Algae.Writer.new({Generator.generate(0), Generator.generate("")})
end
================================================
FILE: lib/algae/writer/monad.ex
================================================
import TypeClass
definst Witchcraft.Monad, for: Algae.Writer
================================================
FILE: lib/algae/writer.ex
================================================
defmodule Algae.Writer do
@moduledoc ~S"""
`Algae.Writer` helps capture the pattern of writing to a pure log or accumulated
value, handling the bookkeeping for you.
If `Algae.Reader` is quasi-read-only, `Algae.Writer` is quasi-write-only.
This is often used for loggers, but could be anything as long as the hidden value
is a `Witchcraft.Monoid`.
There are many applications of `Writer`s, but as an illustrative point,
one could use it for logging across processes and time, since the log
is carried around with the result in a pure fashion. The monadic DSL
helps make using these feel more natural.
For an illustrated guide to `Writer`s,
see [Thee Useful Monads](http://adit.io/posts/2013-06-10-three-useful-monads.html#the-state-monad).
## Anatomy
%Algae.Writer{writer: {value, log}}
↑ ↑
# "explicit" value position "hidden" position,
# commonly used as a log
## Examples
iex> use Witchcraft
...>
...> excite =
...> fn string ->
...> monad writer({0.0, "log"}) do
...> tell string
...>
...> excited <- return "#{string}!"
...> tell " => #{excited} ... "
...>
...> return excited
...> end
...> end
...>
...> {_, logs} =
...> "Hi"
...> |> excite.()
...> >>> excite
...> >>> excite
...> |> censor(&String.trim_trailing(&1, " ... "))
...> |> run()
...>
...> logs
"Hi => Hi! ... Hi! => Hi!! ... Hi!! => Hi!!!"
iex> use Witchcraft
...>
...> exponent =
...> fn num ->
...> monad writer({0, 0}) do
...> tell 1
...> return num * num
...> end
...> end
...>
...> initial = 42
...> {result, times} = run(exponent.(initial) >>> exponent >>> exponent)
...>
...> "#{initial}^#{round(:math.pow(2, times))} = #{result}"
"42^8 = 9682651996416"
"""
alias __MODULE__
alias Witchcraft.{Monoid, Unit}
use Witchcraft
@type log :: Monoid.t()
@type value :: any()
@type writer :: {Writer.value(), Writer.log()}
@type t :: %Writer{writer: writer()}
defstruct writer: {0, []}
@doc """
Construct a `Algae.Writer` struct from a starting value and log.
## Examples
iex> new()
%Algae.Writer{writer: {0, []}}
iex> new("hi")
%Algae.Writer{writer: {"hi", []}}
iex> new("ohai", 42)
%Algae.Writer{writer: {"ohai", 42}}
"""
@spec new(any(), Monoid.t()) :: Writer.t()
def new(value \\ 0, log \\ []), do: %Writer{writer: {value, log}}
@doc """
Similar to `new/2`, but taking a tuple rather than separate fields.
## Examples
iex> writer({"ohai", 42})
%Algae.Writer{writer: {"ohai", 42}}
"""
@spec writer(Writer.writer()) :: Writer.t()
def writer({value, log}), do: new(value, log)
@doc ~S"""
Extract the enclosed value and log from an `Algae.Writer`.
## Examples
iex> run(%Algae.Writer{writer: {"hi", "there"}})
{"hi", "there"}
iex> use Witchcraft
...>
...> half =
...> fn num ->
...> monad writer({0.0, ["log"]}) do
...> let half = num / 2
...> tell ["#{num} / 2 = #{half}"]
...> return half
...> end
...> end
...>
...> run(half.(42) >>> half >>> half)
{
5.25,
[
"42 / 2 = 21.0",
"21.0 / 2 = 10.5",
"10.5 / 2 = 5.25"
]
}
"""
@spec run(Writer.t()) :: Writer.value()
def run(%Writer{writer: writer}), do: writer
@doc ~S"""
Set the "log" portion of an `Algae.Writer` step
## Examples
iex> tell("secrets")
%Algae.Writer{writer: {%Witchcraft.Unit{}, "secrets"}}
iex> use Witchcraft
...>
...> monad %Algae.Writer{writer: {"string", 1}} do
...> tell 42
...> tell 43
...> return "hey"
...> end
%Algae.Writer{writer: {"hey", 85}}
iex> use Witchcraft
...>
...> half =
...> fn num ->
...> monad writer({0.0, ["log"]}) do
...> let half = num / 2
...> tell ["#{num} / 2 = #{half}"]
...> return half
...> end
...> end
...>
...> run(half.(42.0) >>> half >>> half)
{
5.25,
[
"42.0 / 2 = 21.0",
"21.0 / 2 = 10.5",
"10.5 / 2 = 5.25"
]
}
"""
@spec tell(Writer.log()) :: Writer.t()
def tell(log), do: new(%Unit{}, log)
@doc """
Copy the log into the value position. This makes it accessible in do-notation.
## Examples
iex> listen(%Algae.Writer{writer: {42, "hi"}})
%Algae.Writer{writer: {{42, "hi"}, "hi"}}
iex> use Witchcraft
...>
...> monad new(1, 1) do
...> wr <- listen tell(42)
...> tell 43
...> return wr
...> end
%Algae.Writer{
writer: {{%Witchcraft.Unit{}, 42}, 85}
}
"""
@spec listen(Writer.t()) :: Writer.t()
def listen(%Writer{writer: {value, log}}), do: %Writer{writer: {{value, log}, log}}
@doc """
Similar to `listen/1`, but with the ability to adjust the copied log.
## Examples
iex> listen(%Algae.Writer{writer: {1, "hi"}}, &String.upcase/1)
%Algae.Writer{
writer: {{1, "HI"}, "hi"}
}
"""
@spec listen(Writer.t(), (log() -> log())) :: Writer.t()
def listen(writer, fun) do
monad writer do
{value, log} <- listen writer
return {value, fun.(log)}
end
end
@doc ~S"""
Run a function in the value portion of an `Algae.Writer` on the log.
Notice that the structure is similar to what somes out of `listen/{1,2}`
Algae.Writer{writer: {{_, function}, log}}
## Examples
iex> pass(%Algae.Writer{writer: {{1, fn x -> x * 10 end}, 42}})
%Algae.Writer{writer: {1, 420}}
iex> use Witchcraft
...>
...> monad new("string", ["logs"]) do
...> a <- ["start"] |> tell() |> listen()
...> tell ["middle"]
...>
...> {value, logs} <- return a
...> pass writer({{value, fn [log | _] -> [log | [log | logs]] end}, logs})
...>
...> tell ["next is 42"]
...> return 42
...> end
%Algae.Writer{
writer: {42, ["start", "middle", "start", "start", "start", "next is 42"]}
}
"""
@spec pass(Writer.t()) :: Writer.t()
def pass(%Writer{writer: {{value, fun}, log}}), do: %Writer{writer: {value, fun.(log)}}
@doc ~S"""
Run a writer, and run a function over the resulting log.
## Examples
iex> 42
...> |> new(["hi", "THERE", "friend"])
...> |> censor(&Enum.reject(&1, fn log -> String.upcase(log) == log end))
...> |> run()
{42, ["hi", "friend"]}
iex> use Witchcraft
...>
...> 0
...> |> new(["logs"])
...> |> monad do
...> tell ["Start"]
...> tell ["BANG!"]
...> tell ["shhhhhhh..."]
...> tell ["LOUD NOISES!!!"]
...> tell ["End"]
...>
...> return 42
...> end
...> |> censor(&Enum.reject(&1, fn log -> String.upcase(log) == log end))
...> |> run()
{42, ["Start", "shhhhhhh...", "End"]}
"""
@spec censor(Writer.t(), (any() -> any())) :: Writer.t()
def censor(writer, fun) do
pass(monad writer do
value <- writer
return {value, fun}
end)
end
end
================================================
FILE: lib/algae.ex
================================================
defmodule Algae do
@moduledoc """
Builder DSL to handle common ADT definition use cases
"""
import Algae.Internal
@type ast() :: {atom(), any(), any()}
@doc ~S"""
Build a product type
Includes:
* Struct
* Type definition
* Constructor function (for piping and defaults)
* Implicit defaults for simple values
## Definition
For convenveniece, several variants of the DSL are available.
### Standard
defmodule Player do
# =============== #
# Data Definition #
# =============== #
defdata do
name :: String.t()
hit_points :: non_neg_integer()
experience :: non_neg_integer()
end
# =================== #
# Rest of Module #
# (business as usual) #
# =================== #
@spec attack(t(), t()) :: {t(), t()}
def attack(%{experience: xp} = player, %{hit_points: hp} = target) do
{
%{player | experience: xp + 50},
%{target | hit_points: hp - 10}
}
end
end
#=> %Player{name: "Sir Bob", hit_points: 10, experience: 500}
### Single Field Shorthand
Without any fields specified, Algae will default to a single field with
the same name as the module (essentially a "wrapper type"). You must still
provide the type for this field, however.
Embedded in another module:
defmodule Id do
defdata any()
end
%Id{}
#=> %Id{id: nil}
Standalone:
defdata Wrapper :: any()
%Wrapper{}
#=> %Wrapper{wrapper: nil}
## Constructor
A helper function, especially useful for piping. The order of arguments is
the same as the order that they are defined in.
defmodule Person do
defdata do
name :: String.t()
age :: non_neg_integer()
end
end
Person.new("Rachel Weintraub")
#=> %Person{
# name: "Rachel Weintraub",
# age: 0
# }
### Constructor Defaults
Fields will automatically default to a sensible value (a typical "zero" for
that datatype). For example, `non_neg_integer()` will default to `0`,
and `String.t()` will default to `""`.
You may also overwrite these defaults with the `\\\\` syntax.
defmodule Pet do
defdata do
name :: String.t()
leg_count :: non_neg_integer() \\\\ 4
end
end
Pet.new("Crookshanks")
#=> %Pet{
# name: "Crookshanks",
# leg_count: 4
# }
Pet.new("Paul the Psychic Octopus", 8)
#=> %Pet{
# name: "Paul the Psychic Octopus",
# leg_count: 8
# }
This overwriting syntax is _required_ for complex types:
defdata Grocery do
item :: {String.t(), integer(), boolean()} \\\\ {"Apple", 4, false}
end
Grocery.new()
#=> %Grocery{
# item: {"Apple", 4, false}
# }
### Overwrite Constructor
The `new` constructor function may be overwritten.
iex> defmodule Constant do
...> defdata fun()
...>
...> def new(value), do: %Constant{constant: fn _ -> value end}
...> end
...>
...> fourty_two = Constant.new(42)
...> fourty_two.constant.(33)
42
## Empty Tag
An empty type (with no fields) is definable using the `none`() type
defmodule Nothing do
defdata none()
end
Nothing.new()
#=> %Nothing{}
"""
defmacro defdata(ast) do
caller_module = __CALLER__.module
case ast do
{:none, _, _} = type ->
embedded_data_ast()
{:\\, _, [{:::, _, [module_ctx, type]}, default]} ->
caller_module
|> modules(module_ctx)
|> data_ast(default, type)
{:\\, _, [type, default]} ->
caller_module
|> List.wrap()
|> embedded_data_ast(default, type)
{:::, _, [module_ctx, {:none, _, _} = type]} ->
caller_module
|> modules(module_ctx)
|> data_ast(type)
{:::, _, [module_ctx, type]} ->
caller_module
|> modules(module_ctx)
|> data_ast(default_value(type), type)
{_, _, _} = type ->
data_ast(caller_module, type)
[do: {:__block__, _, lines}] ->
data_ast(lines, __CALLER__)
[do: line] ->
data_ast([line], __CALLER__)
end
end
defmacro defdata(module_ctx, do: body) do
module_name =
__CALLER__.module
|> modules(module_ctx)
|> Module.concat()
inner =
body
|> case do
{:__block__, _, lines} -> lines
line -> List.wrap(line)
end
|> data_ast(__CALLER__)
quote do
defmodule unquote(module_name) do
unquote(inner)
end
end
end
@doc """
Build a sum (coproduct) type from product types
defmodule Light do
# ============== #
# Sum Definition #
# ============== #
defsum do
defdata Red :: none()
defdata Yellow :: none()
defdata Green :: none()
end
# =================== #
# Rest of Module #
# (business as usual) #
# =================== #
def from_number(1), do: %Light.Red{}
def from_number(2), do: %Light.Yellow{}
def from_number(3), do: %Light.Green{}
end
Light.new()
#=> %Light.Red{}
## Embedded Products
Data with multiple fileds can be defined directly as part of a sum
defmodule Pet do
defsum do
defdata Cat do
name :: String.t()
claw_sharpness :: String.t()
end
defdata Dog do
name :: String.t()
bark_loudness :: non_neg_integer()
end
end
end
## Default Constructor
The first `defdata`'s constructor will be the default constructor for the sum
defmodule Maybe do
defsum do
defdata Nothing :: none()
defdata Just :: any()
end
end
Maybe.new()
#=> %Maybe.Nothing{}
## Tagged Unions
Sums join existing types with tags: new types to help distibguish the context
that they are in (the sum type)
defdata Book :: String.t() \\\\ "War and Peace"
defdata Video :: String.t() \\\\ "2001: A Space Odyssey"
defmodule Media do
defsum do
defdata Paper :: Book.t()
defdata Film :: Video.t() \\\\ Video.new("A Clockwork Orange")
end
end
media = Media.new()
#=> %Paper{
# paper: %Book{
# book: "War and Peace"
# }
# }
"""
@spec defsum([do: {:__block__, [any()], ast()}]) :: ast()
defmacro defsum(do: {:__block__, _, [first | _] = parts} = block) do
module_ctx = __CALLER__.module
types = or_types(parts, module_ctx)
default_module =
module_ctx
|> List.wrap()
|> Kernel.++(submodule_name(first))
|> Module.concat()
quote do
@type t :: unquote(types)
unquote(block)
@spec new() :: t()
def new, do: unquote(default_module).new()
defoverridable [new: 0]
end
end
end
================================================
FILE: mix.exs
================================================
defmodule Algae.Mixfile do
use Mix.Project
def project do
[
app: :algae,
aliases: aliases(),
deps: deps(),
preferred_cli_env: [quality: :test],
# Versions
version: "1.3.1",
elixir: "~> 1.9",
elixirc_paths: elixirc_paths(Mix.env()),
# Docs
name: "Algae",
docs: docs(),
# Hex
description: "Bootstrapped algebraic data types for Elixir",
package: package()
]
end
defp aliases do
[
quality: [
"test",
"credo --strict"
]
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
defp deps do
[
{:credo, "~> 1.5", only: [:dev, :test], runtime: false},
{:inch_ex, "~> 2.0", only: [:dev, :docs, :test], runtime: false},
{:dialyxir, "~> 1.1", only: :dev, runtime: false},
{:earmark, "~> 1.4", only: :dev, runtime: false},
{:ex_doc, "~> 0.23", only: :dev, runtime: false},
{:quark, "~> 2.2"},
{:type_class, "~> 1.2"},
{:witchcraft, "~> 1.0"},
]
end
defp docs do
[
extras: ["README.md"],
logo: "./brand/mini-logo.png",
main: "readme",
source_url: "https://github.com/witchcrafters/algae"
]
end
defp package do
[
licenses: ["Apache-2.0"],
links: %{"GitHub" => "https://github.com/witchcrafters/algae"},
maintainers: ["Brooklyn Zelenka", "Steven Vandevelde"]
]
end
end
================================================
FILE: shell.nix
================================================
let
nixpkgs = import (fetchTarball {
# Run `cachix use jechol` to use compiled binary cache.
url = "https://github.com/jechol/nixpkgs/archive/21.11-otp24-no-jit.tar.gz";
sha256 = "sha256:1lka707hrnkp70vny99m9fmp4a8136vl7addmpfsdvkwb81d1jk9";
}) { };
platform = if nixpkgs.stdenv.isDarwin then [
nixpkgs.darwin.apple_sdk.frameworks.CoreServices
nixpkgs.darwin.apple_sdk.frameworks.Foundation
] else if nixpkgs.stdenv.isLinux then
[ nixpkgs.inotify-tools ]
else
[ ];
in nixpkgs.mkShell {
buildInputs = with nixpkgs;
[
# OTP
erlang
elixir
] ++ platform;
}
================================================
FILE: test/algae_dsl_aliasing_test.exs
================================================
defmodule AlgaeDslAliasingTest.Base do
import Algae
alias __MODULE__
defmodule A do
defdata do
a :: String.t()
end
end
defmodule B do
defdata do
b :: Base.A.t() \\ Base.A.new("a for amazing!")
end
end
defmodule C do
defdata do
c :: Base.B.t()
end
end
end
================================================
FILE: test/algae_test.exs
================================================
defmodule AlgaeTest do
alias Example.{Animal, Book, Media, Wrapper}
use ExUnit.Case
doctest Algae, import: true
doctest Algae.Id, import: true
doctest Algae.Maybe, import: true
doctest Algae.Either, import: true
doctest Algae.Free, import: true
doctest Algae.Tree.BinarySearch, import: true
doctest Algae.Tree.Rose, import: true
doctest Algae.Reader, import: true
doctest Algae.Writer, import: true
doctest Algae.State, import: true
test "constructor for empty type" do
assert Example.Light.new() == %Example.Light.Red{}
end
test "constructor with one field" do
assert %Example.Wrapper{} == %Wrapper{wrapper: nil}
end
test "constructor with multiple fields uses defaults" do
crookshanks =
%Animal{
name: "Crookshanks",
leg_count: 4
}
assert Animal.new("Crookshanks") == crookshanks
end
test "constructor with multiple fields can overwrite all fields" do
paul =
%Animal{
name: "Paul the Psychic Octopus",
leg_count: 8
}
assert Animal.new("Paul the Psychic Octopus", 8) == paul
end
test "sum constructor uses the first tagged type" do
paper =
%Media.Paper{
paper: %Book{
book: "War and Peace"
}
}
assert Media.new() == paper
end
test "test either keeps left state using convey" do
use Witchcraft
r_val = Algae.Either.Right.new("right!")
r_fun = Algae.Either.Right.new(fn x -> "who's there? " <> x end)
l_val = Algae.Either.Left.new("left the building!!!")
assert convey(r_val, r_fun) == Algae.Either.Right.new("who's there? right!")
assert convey(l_val, r_fun) == l_val
assert convey(l_val, l_val) == l_val
assert convey(r_val, l_val) == l_val
end
end
================================================
FILE: test/support/example.ex
================================================
import Algae
defmodule Example do
@moduledoc false
defdata Complex :: ([{:ok, integer()}] | number()) \\ 22
defdata Any :: any()
defdata Int :: integer()
defdata None :: none()
defmodule Embedded.One do
@moduledoc false
defdata do: quux :: any() \\ 22
end
defmodule Embedded.Many do
@moduledoc false
defdata do
first :: any()
second :: integer() \\ 42
end
end
defdata Bare do
first :: any()
second :: non_neg_integer() \\ 22
third :: any()
end
defmodule Simple do
@moduledoc false
defdata any()
end
defmodule Sum.Lights do
@moduledoc false
defsum do
defdata Red :: any() \\ 22
defdata Yellow :: any()
defdata Green :: none()
end
end
defmodule Sum.Maybe do
@moduledoc false
defsum do
defdata Just do
value :: any()
end
defdata Nada :: none()
end
end
defmodule Player do
@moduledoc false
# =============== #
# Data Definition #
# =============== #
defdata do
name :: String.t()
hit_points :: non_neg_integer()
experience :: non_neg_integer()
end
# =================== #
# Rest of Module #
# (business as usual) #
# =================== #
@spec attack(t(), t()) :: {t(), t()}
def attack(player = %{experience: xp}, target = %{hit_points: hp}) do
{
%{player | experience: xp + 50},
%{target | hit_points: hp - 10}
}
end
end
defmodule Id do
@moduledoc false
defdata any()
end
defdata Wrapper :: any()
defmodule Person do
@moduledoc false
defdata do
name :: String.t()
age :: non_neg_integer()
end
end
defmodule Animal do
@moduledoc false
defdata do
name :: String.t()
leg_count :: non_neg_integer() \\ 4
end
end
defdata Grocery do
item :: {String.t(), integer(), boolean()} \\ {"Apple", 4, false}
end
defmodule Constant do
@moduledoc false
defdata fun()
def new(value), do: %Constant{constant: fn _ -> value end}
end
defmodule Nothing do
@moduledoc false
defdata none()
end
defmodule Light do
@moduledoc false
# ============== #
# Sum Definition #
# ============== #
defsum do
defdata Red :: none()
defdata Yellow :: none()
defdata Green :: none()
end
# =================== #
# Rest of Module #
# (business as usual) #
# =================== #
def from_number(1), do: %Light.Red{}
def from_number(2), do: %Light.Yellow{}
def from_number(3), do: %Light.Green{}
end
defmodule Pet do
@moduledoc false
defsum do
defdata Cat do
name :: String.t()
claw_sharpness :: String.t()
end
defdata Dog do
name :: String.t()
bark_loudness :: non_neg_integer()
end
end
end
defmodule Option do
@moduledoc false
defsum do
defdata None :: none()
defdata Some :: any()
end
end
defdata Book :: String.t() \\ "War and Peace"
defdata Video :: String.t() \\ "2001: A Space Odyssey"
defmodule Media do
@moduledoc false
defsum do
defdata Paper :: Example.Book.t() \\ Example.Book.new()
defdata Film :: Example.Video.t() \\ Example.Video.new("A Clockwork Orange")
end
end
end
================================================
FILE: test/test_helper.exs
================================================
ExUnit.start()
gitextract_pg39seh_/
├── .credo.exs
├── .envrc
├── .github/
│ ├── CODE_OF_CONDUCT.md
│ ├── PULL_REQUEST_TEMPLATE.md
│ └── workflows/
│ ├── ci.yaml
│ └── greetings.yml
├── .gitignore
├── .tool-versions
├── LICENSE
├── README.md
├── brand/
│ └── LOGO_LICENSE
├── lib/
│ ├── algae/
│ │ ├── either.ex
│ │ ├── free.ex
│ │ ├── id/
│ │ │ ├── applicative.ex
│ │ │ ├── apply.ex
│ │ │ ├── chain.ex
│ │ │ ├── comonad.ex
│ │ │ ├── extend.ex
│ │ │ ├── foldable.ex
│ │ │ ├── functor.ex
│ │ │ ├── generator.ex
│ │ │ ├── monad.ex
│ │ │ ├── monoid.ex
│ │ │ ├── ord.ex
│ │ │ ├── semigroup.ex
│ │ │ ├── setoid.ex
│ │ │ └── traversable.ex
│ │ ├── id.ex
│ │ ├── internal/
│ │ │ └── needs_explicit_default_error.ex
│ │ ├── internal.ex
│ │ ├── maybe.ex
│ │ ├── reader/
│ │ │ ├── applicative.ex
│ │ │ ├── apply.ex
│ │ │ ├── chain.ex
│ │ │ ├── functor.ex
│ │ │ ├── generator.ex
│ │ │ └── monad.ex
│ │ ├── reader.ex
│ │ ├── state/
│ │ │ ├── applicative.ex
│ │ │ ├── apply.ex
│ │ │ ├── chain.ex
│ │ │ ├── functor.ex
│ │ │ ├── generator.ex
│ │ │ └── monad.ex
│ │ ├── state.ex
│ │ ├── tree/
│ │ │ ├── binary_search/
│ │ │ │ ├── applicative.ex
│ │ │ │ ├── apply.ex
│ │ │ │ ├── chain.ex
│ │ │ │ ├── extend.ex
│ │ │ │ ├── foldable.ex
│ │ │ │ ├── functor.ex
│ │ │ │ ├── generator.ex
│ │ │ │ ├── monad.ex
│ │ │ │ ├── monoid.ex
│ │ │ │ ├── ord.ex
│ │ │ │ ├── semigroup.ex
│ │ │ │ └── setoid.ex
│ │ │ ├── binary_search.ex
│ │ │ ├── rose/
│ │ │ │ ├── applicative.ex
│ │ │ │ ├── apply.ex
│ │ │ │ ├── chain.ex
│ │ │ │ ├── foldable.ex
│ │ │ │ ├── functor.ex
│ │ │ │ ├── generator.ex
│ │ │ │ └── monad.ex
│ │ │ └── rose.ex
│ │ ├── writer/
│ │ │ ├── applicative.ex
│ │ │ ├── apply.ex
│ │ │ ├── chain.ex
│ │ │ ├── functor.ex
│ │ │ ├── generator.ex
│ │ │ └── monad.ex
│ │ └── writer.ex
│ └── algae.ex
├── mix.exs
├── shell.nix
└── test/
├── algae_dsl_aliasing_test.exs
├── algae_test.exs
├── support/
│ └── example.ex
└── test_helper.exs
SYMBOL INDEX (124 symbols across 16 files)
FILE: lib/algae.ex
class Algae (line 1) | defmodule Algae
FILE: lib/algae/either.ex
class Algae.Either (line 1) | defmodule Algae.Either
FILE: lib/algae/free.ex
class Algae.Free (line 1) | defmodule Algae.Free
method new (line 57) | def new(value), do: %Pure{pure: value}
method layer (line 77) | def layer(free, mutual), do: %Roll{roll: of(mutual, free)}
method wrap (line 93) | def wrap(functor), do: %Roll{roll: functor}
method free (line 111) | def free(functor) do
FILE: lib/algae/id.ex
class Algae.Id (line 1) | defmodule Algae.Id
method new (line 26) | def new(inner), do: %Algae.Id{id: inner}
FILE: lib/algae/internal.ex
class Algae.Internal (line 1) | defmodule Algae.Internal
method data_ast (line 46) | def data_ast(modules, {:none, _, _}) do
method data_ast (line 64) | def data_ast(caller_module, type) do
method data_ast (line 88) | def data_ast(name, default, type_ctx) do
method embedded_data_ast (line 112) | def embedded_data_ast do
method embedded_data_ast (line 123) | def embedded_data_ast(module_ctx, default, type_ctx) do
method module_elements (line 151) | def module_elements(lines, caller) do
method normalize_elements (line 168) | def normalize_elements({:::, _, [{field, _, _}, type]}, caller) do
method normalize_elements (line 173) | def normalize_elements({:\\, _, [{:::, _, [{field, _, _}, type]}, defa...
method resolve_alias (line 178) | def resolve_alias({{_, _, _} = a, b, c}, caller) do
method resolve_alias (line 182) | def resolve_alias({:. = a, b, [{:__aliases__, _, _} = the_alias | rest...
method resolve_alias (line 187) | def resolve_alias(a, _), do: a
method or_types (line 190) | def or_types({:\\, _, [{:::, _, [_, types]}, _]}, module_ctx) do
method or_types (line 194) | def or_types([head | tail], module_ctx) do
method modules (line 201) | def modules(top, module_ctx), do: [top | extract_name(module_ctx)]
method call_type (line 204) | def call_type(new_module, module_ctx) do
method submodule_name (line 211) | def submodule_name({:defdata, _, [{:::, _, [body, _]}]}) do
method submodule_name (line 221) | def submodule_name({:defdata, _, [{:\\, _, [{:::, _, [{:__aliases__, _...
method submodule_name (line 225) | def submodule_name({:defdata, _, [{:__aliases__, _, module}, _]}) do
method extract_name (line 230) | def extract_name({_, _, inner_name}), do: List.wrap(inner_name)
method module_to_field (line 239) | def module_to_field(module) do
method default_value (line 250) | def default_value({{:., _, [{_, _, [:String]}, :t]}, _, _}), do: ""
method default_value (line 251) | def default_value({{:., _, [String, :t]}, _, _}), do: ""
method default_value (line 253) | def default_value({{:., _, [{_, _, adt}, :t]}, _, []}) do
method default_value (line 257) | def default_value({{:., _, [module, :t]}, _, []}) do
method default_value (line 261) | def default_value([_]), do: []
method default_value (line 263) | def default_value({type, _, _}) do
FILE: lib/algae/internal/needs_explicit_default_error.ex
class Algae.Internal.NeedsExplicitDefaultError (line 1) | defmodule Algae.Internal.NeedsExplicitDefaultError
FILE: lib/algae/maybe.ex
class Algae.Maybe (line 1) | defmodule Algae.Maybe
method new (line 71) | def new(nothing_value, [nothing: nothing_value]), do: Nothing.new()
method new (line 72) | def new(value, _), do: Just.new(value)
method new (line 75) | def new(value), do: Just.new(value)
method from_nillable (line 90) | def from_nillable(value), do: new(value, nothing: nil)
method from_maybe (line 105) | def from_maybe(%Nothing{}, [else: fallback]), do: fallback
method from_maybe (line 106) | def from_maybe(%Just{just: inner}, _), do: inner
FILE: lib/algae/reader.ex
class Algae.Reader (line 1) | defmodule Algae.Reader
method new (line 54) | def new(fun), do: %Reader{reader: fun}
method run (line 71) | def run(%Reader{reader: fun}, arg), do: fun.(arg)
method ask (line 98) | def ask, do: Reader.new(fn x -> x end)
method ask (line 128) | def ask(fun) do
method local (line 151) | def local(reader, fun) do
FILE: lib/algae/state.ex
class Algae.State (line 1) | defmodule Algae.State
method default (line 79) | def default(s), do: {s, s}
method new (line 92) | def new(runner), do: %State{runner: runner}
method state (line 104) | def state(runner), do: new(runner)
method run (line 120) | def run(%State{runner: fun}), do: fun
method run (line 137) | def run(%State{runner: fun}, arg), do: fun.(arg)
method put (line 153) | def put(s), do: State.new(fn _ -> {%Unit{}, s} end)
method modify (line 181) | def modify(fun), do: State.new(fn s -> {%Unit{}, fun.(s)} end)
method get (line 193) | def get, do: State.new(fn a -> {a, a} end)
method get (line 208) | def get(fun) do
method evaluate (line 233) | def evaluate(state, value) do
method execute (line 262) | def execute(state, value) do
FILE: lib/algae/tree/binary_search.ex
class Algae.Tree.BinarySearch (line 1) | defmodule Algae.Tree.BinarySearch
method new (line 68) | def new, do: %Empty{}
method new (line 84) | def new(value), do: %Node{node: value}
method insert (line 101) | def insert(%Empty{}, value), do: new(value)
method insert (line 103) | def insert(tree = %Node{node: node, left: left, right: right}, orderab...
method insert (line 111) | def insert(%Empty{}, value), do: new(value)
method insert (line 113) | def insert(tree = %Node{node: node, left: left, right: right}, orderab...
method delete (line 152) | def delete(%Empty{}, _), do: %Empty{}
method delete (line 154) | def delete(tree = %Node{node: node, left: left, right: right}, orderab...
method to_list (line 192) | def to_list(tree), do: Witchcraft.Foldable.to_list(tree)
method to_ordered_list (line 215) | def to_ordered_list(tree), do: tree |> to_list() |> Enum.sort()
method from_list (line 241) | def from_list([]), do: %Empty{}
method from_list (line 242) | def from_list([head | tail]), do: from_list(tail, new(head))
method from_list (line 272) | def from_list([], seed), do: seed
method from_list (line 273) | def from_list([head | tail], seed), do: from_list(tail, insert(seed, h...
FILE: lib/algae/tree/rose.ex
class Algae.Tree.Rose (line 1) | defmodule Algae.Tree.Rose
method new (line 52) | def new(rose), do: %Rose{rose: rose, forest: []}
method new (line 70) | def new(rose, forest), do: %Rose{rose: rose, forest: forest}
method layer (line 103) | def layer(tree, rose), do: %Rose{rose: rose, forest: [tree]}
FILE: lib/algae/writer.ex
class Algae.Writer (line 1) | defmodule Algae.Writer
method new (line 98) | def new(value \\ 0, log \\ []), do: %Writer{writer: {value, log}}
method writer (line 110) | def writer({value, log}), do: new(value, log)
method run (line 143) | def run(%Writer{writer: writer}), do: writer
method tell (line 185) | def tell(log), do: new(%Unit{}, log)
method listen (line 208) | def listen(%Writer{writer: {value, log}}), do: %Writer{writer: {{value...
method listen (line 222) | def listen(writer, fun) do
method pass (line 259) | def pass(%Writer{writer: {{value, fun}, log}}), do: %Writer{writer: {v...
method censor (line 291) | def censor(writer, fun) do
FILE: mix.exs
class Algae.Mixfile (line 1) | defmodule Algae.Mixfile
method project (line 4) | def project do
method aliases (line 26) | defp aliases do
method elixirc_paths (line 35) | defp elixirc_paths(:test), do: ["lib", "test/support"]
method elixirc_paths (line 36) | defp elixirc_paths(_), do: ["lib"]
method deps (line 38) | defp deps do
method docs (line 52) | defp docs do
method package (line 61) | defp package do
FILE: test/algae_dsl_aliasing_test.exs
class AlgaeDslAliasingTest.Base (line 1) | defmodule AlgaeDslAliasingTest.Base
class A (line 6) | defmodule A
class B (line 12) | defmodule B
class C (line 18) | defmodule C
FILE: test/algae_test.exs
class AlgaeTest (line 1) | defmodule AlgaeTest
FILE: test/support/example.ex
class Example (line 3) | defmodule Example
class Embedded.One (line 12) | defmodule Embedded.One
class Embedded.Many (line 18) | defmodule Embedded.Many
class Simple (line 33) | defmodule Simple
class Sum.Lights (line 39) | defmodule Sum.Lights
class Sum.Maybe (line 49) | defmodule Sum.Maybe
class Player (line 61) | defmodule Player
method attack (line 80) | def attack(player = %{experience: xp}, target = %{hit_points: hp}) do
class Id (line 88) | defmodule Id
class Person (line 96) | defmodule Person
class Animal (line 105) | defmodule Animal
class Constant (line 118) | defmodule Constant
method new (line 123) | def new(value), do: %Constant{constant: fn _ -> value end}
class Nothing (line 126) | defmodule Nothing
class Light (line 132) | defmodule Light
method from_number (line 150) | def from_number(1), do: %Light.Red{}
method from_number (line 151) | def from_number(2), do: %Light.Yellow{}
method from_number (line 152) | def from_number(3), do: %Light.Green{}
class Pet (line 155) | defmodule Pet
class Option (line 171) | defmodule Option
class Media (line 183) | defmodule Media
Condensed preview — 80 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (126K chars).
[
{
"path": ".credo.exs",
"chars": 341,
"preview": "%{\n configs: [\n %{\n name: \"default\",\n files: %{\n included: [\"lib/\", \"test\"],\n excluded: []\n "
},
{
"path": ".envrc",
"chars": 76,
"preview": "use nix\n\nexport MIX_HOME=$(pwd)/.mix\nexport PATH=$PATH:$(pwd)/.mix/escripts\n"
},
{
"path": ".github/CODE_OF_CONDUCT.md",
"chars": 5484,
"preview": "# Code of Conduct\n\n## 1. Purpose\n\nA primary goal of Witchcrafters is to be inclusive to the largest number of contributo"
},
{
"path": ".github/PULL_REQUEST_TEMPLATE.md",
"chars": 1313,
"preview": "A similar PR may already be submitted!\nPlease search among the [Pull request](../) before creating one.\n\nThanks for subm"
},
{
"path": ".github/workflows/ci.yaml",
"chars": 565,
"preview": "on:\n push: { \"branches\": [ \"main\" ] }\n pull_request: { \"branches\": [ \"main\" ] }\n\njobs:\n test:\n runs-on: ub"
},
{
"path": ".github/workflows/greetings.yml",
"chars": 404,
"preview": "name: Greetings\n\non: [pull_request, issues]\n\njobs:\n greeting:\n runs-on: ubuntu-latest\n steps:\n - uses: actions"
},
{
"path": ".gitignore",
"chars": 68,
"preview": "/_build\n/cover\n/deps\n/doc\nerl_crash.dump\n*.ez\n*.beam\n.DS_Store\n.mix\n"
},
{
"path": ".tool-versions",
"chars": 25,
"preview": "erlang 24.2\nelixir 1.13.2"
},
{
"path": "LICENSE",
"chars": 1083,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2017 Brooklyn Zelenka\n\nPermission is hereby granted, free of charge, to any person "
},
{
"path": "README.md",
"chars": 7480,
"preview": "\n\n[ Lyngb., herbarium sheet. Colle"
},
{
"path": "lib/algae/either.ex",
"chars": 5239,
"preview": "defmodule Algae.Either do\n @moduledoc ~S\"\"\"\n Represent branching conditions. These could be different return types,\n "
},
{
"path": "lib/algae/free.ex",
"chars": 5879,
"preview": "defmodule Algae.Free do\n @moduledoc \"\"\"\n A \"free\" structure that converts functors into monads by embedding them in\n "
},
{
"path": "lib/algae/id/applicative.ex",
"chars": 113,
"preview": "import TypeClass\n\ndefinst Witchcraft.Applicative, for: Algae.Id do\n def of(_, data), do: Algae.Id.new(data)\nend\n"
},
{
"path": "lib/algae/id/apply.ex",
"chars": 131,
"preview": "import TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Apply, for: Algae.Id do\n def convey(data, %{id: fun}), do: map(data"
},
{
"path": "lib/algae/id/chain.ex",
"chars": 113,
"preview": "import TypeClass\n\ndefinst Witchcraft.Chain, for: Algae.Id do\n def chain(%{id: data}, link), do: link.(data)\nend\n"
},
{
"path": "lib/algae/id/comonad.ex",
"chars": 106,
"preview": "import TypeClass\n\ndefinst Witchcraft.Comonad, for: Algae.Id do\n def extract(%{id: inner}), do: inner\nend\n"
},
{
"path": "lib/algae/id/extend.ex",
"chars": 109,
"preview": "import TypeClass\n\ndefinst Witchcraft.Extend, for: Algae.Id do\n def nest(inner), do: Algae.Id.new(inner)\nend\n"
},
{
"path": "lib/algae/id/foldable.ex",
"chars": 131,
"preview": "import TypeClass\n\ndefinst Witchcraft.Foldable, for: Algae.Id do\n def right_fold(%{id: data}, seed, fun), do: fun.(data,"
},
{
"path": "lib/algae/id/functor.ex",
"chars": 133,
"preview": "import TypeClass\n\ndefinst Witchcraft.Functor, for: Algae.Id do\n def map(%{id: data}, fun), do: data |> fun.() |> Algae."
},
{
"path": "lib/algae/id/generator.ex",
"chars": 197,
"preview": "defimpl TypeClass.Property.Generator, for: Algae.Id do\n def generate(_) do\n [1, 1.1, \"\", []]\n |> Enum.random()\n "
},
{
"path": "lib/algae/id/monad.ex",
"chars": 57,
"preview": "import TypeClass\ndefinst Witchcraft.Monad, for: Algae.Id\n"
},
{
"path": "lib/algae/id/monoid.ex",
"chars": 152,
"preview": "import TypeClass\n\ndefinst Witchcraft.Monoid, for: Algae.Id do\n def empty(%{id: sample}), do: sample |> Witchcraft.Monoi"
},
{
"path": "lib/algae/id/ord.ex",
"chars": 253,
"preview": "import TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Ord, for: Algae.Id do\n custom_generator(_) do\n 1\n |> TypeClas"
},
{
"path": "lib/algae/id/semigroup.ex",
"chars": 251,
"preview": "import TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Semigroup, for: Algae.Id do\n custom_generator(_) do\n 1\n |> Ty"
},
{
"path": "lib/algae/id/setoid.ex",
"chars": 131,
"preview": "import TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Setoid, for: Algae.Id do\n def equivalent?(%{id: a}, %{id: b}), do: "
},
{
"path": "lib/algae/id/traversable.ex",
"chars": 181,
"preview": "import TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Traversable, for: Algae.Id do\n def traverse(%{id: data}, link) do\n "
},
{
"path": "lib/algae/id.ex",
"chars": 400,
"preview": "defmodule Algae.Id do\n @moduledoc ~S\"\"\"\n The simplest ADT: a simple wrapper for some data\n\n ## Examples\n\n iex> %"
},
{
"path": "lib/algae/internal/needs_explicit_default_error.ex",
"chars": 113,
"preview": "defmodule Algae.Internal.NeedsExplicitDefaultError do\n defexception message: \"Needs explicit default value\"\nend\n"
},
{
"path": "lib/algae/internal.ex",
"chars": 8023,
"preview": "defmodule Algae.Internal do\n @moduledoc false\n\n @type ast() :: {atom(), any(), any()}\n\n @doc \"\"\"\n Construct a data t"
},
{
"path": "lib/algae/maybe.ex",
"chars": 6076,
"preview": "defmodule Algae.Maybe do\n @moduledoc ~S\"\"\"\n The sum of `Algae.Maybe.Just` and `Algae.Maybe.Nothing`.\n Maybe represent"
},
{
"path": "lib/algae/reader/applicative.ex",
"chars": 195,
"preview": "alias Algae.Reader\nimport TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Applicative, for: Algae.Reader do\n @force_ty"
},
{
"path": "lib/algae/reader/apply.ex",
"chars": 270,
"preview": "alias Algae.Reader\nimport TypeClass\n\nuse Quark\nuse Witchcraft\n\ndefinst Witchcraft.Apply, for: Algae.Reader do\n @force_"
},
{
"path": "lib/algae/reader/chain.ex",
"chars": 263,
"preview": "import TypeClass\n\ndefinst Witchcraft.Chain, for: Algae.Reader do\n @force_type_instance true\n alias Algae.Reader\n\n de"
},
{
"path": "lib/algae/reader/functor.ex",
"chars": 229,
"preview": "alias Algae.Reader\nimport TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Functor, for: Algae.Reader do\n @force_type_i"
},
{
"path": "lib/algae/reader/generator.ex",
"chars": 181,
"preview": "defimpl TypeClass.Property.Generator, for: Algae.Reader do\n def generate(_) do\n fn -> nil end\n |> TypeClass.Prope"
},
{
"path": "lib/algae/reader/monad.ex",
"chars": 97,
"preview": "import TypeClass\n\ndefinst Witchcraft.Monad, for: Algae.Reader do\n @force_type_instance true\nend\n"
},
{
"path": "lib/algae/reader.ex",
"chars": 3764,
"preview": "defmodule Algae.Reader do\n @moduledoc ~S\"\"\"\n `Algae.Reader` allows you to pass some readable context around through ac"
},
{
"path": "lib/algae/state/applicative.ex",
"chars": 171,
"preview": "import TypeClass\n\ndefinst Witchcraft.Applicative, for: Algae.State do\n @force_type_instance true\n def of(_, value), do"
},
{
"path": "lib/algae/state/apply.ex",
"chars": 333,
"preview": "alias Algae.State\nimport TypeClass\n\ndefinst Witchcraft.Apply, for: Algae.State do\n @force_type_instance true\n def con"
},
{
"path": "lib/algae/state/chain.ex",
"chars": 247,
"preview": "alias Algae.State\nimport TypeClass\n\ndefinst Witchcraft.Chain, for: Algae.State do\n @force_type_instance true\n\n def ch"
},
{
"path": "lib/algae/state/functor.ex",
"chars": 401,
"preview": "alias Algae.State\nimport TypeClass\n\ndefinst Witchcraft.Functor, for: Algae.State do\n @force_type_instance true\n\n def "
},
{
"path": "lib/algae/state/generator.ex",
"chars": 241,
"preview": "defimpl TypeClass.Property.Generator, for: Algae.State do\n def generate(_) do\n inner =\n [0, 1.1, \"\", []]\n "
},
{
"path": "lib/algae/state/monad.ex",
"chars": 96,
"preview": "import TypeClass\n\ndefinst Witchcraft.Monad, for: Algae.State do\n @force_type_instance true\nend\n"
},
{
"path": "lib/algae/state.ex",
"chars": 5924,
"preview": "defmodule Algae.State do\n @moduledoc ~S\"\"\"\n `Algae.State` describes a wrapped function that can be used to pass around"
},
{
"path": "lib/algae/tree/binary_search/applicative.ex",
"chars": 326,
"preview": "alias Algae.Tree.BinarySearch.Node\nimport TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Applicative, for: Algae.Tree.Bina"
},
{
"path": "lib/algae/tree/binary_search/apply.ex",
"chars": 532,
"preview": "alias Algae.Tree.BinarySearch.{Empty, Node}\nimport TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Apply, for: Algae.Tree.B"
},
{
"path": "lib/algae/tree/binary_search/chain.ex",
"chars": 299,
"preview": "alias Algae.Tree.BinarySearch.{Empty, Node}\nimport TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Chain, for: Algae.Tree.B"
},
{
"path": "lib/algae/tree/binary_search/extend.ex",
"chars": 425,
"preview": "alias Algae.Tree.BinarySearch.{Empty, Node}\nimport TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Extend, for: Algae.Tree."
},
{
"path": "lib/algae/tree/binary_search/foldable.ex",
"chars": 512,
"preview": "alias Algae.Tree.BinarySearch.Node\nimport TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Foldable, for: Algae.Tree.BinaryS"
},
{
"path": "lib/algae/tree/binary_search/functor.ex",
"chars": 445,
"preview": "alias Algae.Tree.BinarySearch.{Empty, Node}\nalias Witchcraft.Functor\nimport TypeClass\n\ndefinst Witchcraft.Functor, for"
},
{
"path": "lib/algae/tree/binary_search/generator.ex",
"chars": 751,
"preview": "alias Algae.Tree.BinarySearch.{Empty, Node}\nuse Witchcraft\n\ndefimpl TypeClass.Property.Generator, for: Algae.Tree.Binary"
},
{
"path": "lib/algae/tree/binary_search/monad.ex",
"chars": 191,
"preview": "import TypeClass\nuse Witchcraft\n\ndefinst(Witchcraft.Monad, for: Algae.Tree.BinarySearch.Empty)\n\ndefinst Witchcraft.Monad"
},
{
"path": "lib/algae/tree/binary_search/monoid.ex",
"chars": 315,
"preview": "alias Algae.Tree.BinarySearch, as: BST\nalias Algae.Tree.BinarySearch.{Empty, Node}\n\nimport TypeClass\n\nuse Witchcraft\n\nde"
},
{
"path": "lib/algae/tree/binary_search/ord.ex",
"chars": 796,
"preview": "alias Algae.Tree.BinarySearch.{Empty, Node}\nimport TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Ord, for: Algae.Tree.Bin"
},
{
"path": "lib/algae/tree/binary_search/semigroup.ex",
"chars": 516,
"preview": "alias Algae.Tree.BinarySearch, as: BST\nalias Algae.Tree.BinarySearch.{Empty, Node}\n\nimport TypeClass\nuse Witchcraft\n\ndef"
},
{
"path": "lib/algae/tree/binary_search/setoid.ex",
"chars": 486,
"preview": "alias Algae.Tree.BinarySearch, as: BST\nalias Algae.Tree.BinarySearch.{Empty, Node}\n\nimport TypeClass\n\nuse Witchcraft\n\nde"
},
{
"path": "lib/algae/tree/binary_search.ex",
"chars": 6672,
"preview": "defmodule Algae.Tree.BinarySearch do\n @moduledoc \"\"\"\n Represent a `BinarySearch` tree.\n\n ## Examples\n\n iex> alia"
},
{
"path": "lib/algae/tree/rose/applicative.ex",
"chars": 129,
"preview": "import TypeClass\n\ndefinst Witchcraft.Applicative, for: Algae.Tree.Rose do\n def of(_, value), do: Algae.Tree.Rose.new(va"
},
{
"path": "lib/algae/tree/rose/apply.ex",
"chars": 418,
"preview": "alias Algae.Tree.Rose\nalias Witchcraft.{Apply, Functor}\nimport TypeClass\n\ndefinst Witchcraft.Apply, for: Algae.Tree.Ro"
},
{
"path": "lib/algae/tree/rose/chain.ex",
"chars": 364,
"preview": "alias Algae.Tree.Rose\nalias Witchcraft.{Chain, Functor}\nimport TypeClass\n\ndefinst Witchcraft.Chain, for: Algae.Tree.Ro"
},
{
"path": "lib/algae/tree/rose/foldable.ex",
"chars": 250,
"preview": "alias Algae.Tree.Rose\nalias Witchcraft.Foldable\nimport TypeClass\n\ndefinst Witchcraft.Foldable, for: Algae.Tree.Rose do"
},
{
"path": "lib/algae/tree/rose/functor.ex",
"chars": 282,
"preview": "alias Algae.Tree.Rose\nalias Witchcraft.Functor\nimport TypeClass\n\ndefinst Witchcraft.Functor, for: Algae.Tree.Rose do\n "
},
{
"path": "lib/algae/tree/rose/generator.ex",
"chars": 565,
"preview": "alias Algae.Tree.Rose\nalias TypeClass.Property.Generator\n\ndefimpl TypeClass.Property.Generator, for: Algae.Tree.Rose d"
},
{
"path": "lib/algae/tree/rose/monad.ex",
"chars": 65,
"preview": "import TypeClass\n\ndefinst Witchcraft.Monad, for: Algae.Tree.Rose\n"
},
{
"path": "lib/algae/tree/rose.ex",
"chars": 1972,
"preview": "defmodule Algae.Tree.Rose do\n @moduledoc \"\"\"\n A tree with any number of nodes at each level\n\n ## Examples\n\n %Alg"
},
{
"path": "lib/algae/writer/applicative.ex",
"chars": 191,
"preview": "alias Algae.Writer\nimport TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Applicative, for: Algae.Writer do\n def of(%W"
},
{
"path": "lib/algae/writer/apply.ex",
"chars": 245,
"preview": "alias Algae.Writer\nimport TypeClass\n\nuse Quark\nuse Witchcraft\n\ndefinst Witchcraft.Apply, for: Algae.Writer do\n def con"
},
{
"path": "lib/algae/writer/chain.ex",
"chars": 280,
"preview": "alias Algae.Writer\nimport TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Chain, for: Algae.Writer do\n def chain(%Writ"
},
{
"path": "lib/algae/writer/functor.ex",
"chars": 189,
"preview": "alias Algae.Writer\nimport TypeClass\nuse Witchcraft\n\ndefinst Witchcraft.Functor, for: Algae.Writer do\n def map(%Writ"
},
{
"path": "lib/algae/writer/generator.ex",
"chars": 188,
"preview": "alias TypeClass.Property.Generator\n\ndefimpl TypeClass.Property.Generator, for: Algae.Writer do\n def generate(_), do: Al"
},
{
"path": "lib/algae/writer/monad.ex",
"chars": 62,
"preview": "import TypeClass\n\ndefinst Witchcraft.Monad, for: Algae.Writer\n"
},
{
"path": "lib/algae/writer.ex",
"chars": 7541,
"preview": "defmodule Algae.Writer do\n @moduledoc ~S\"\"\"\n `Algae.Writer` helps capture the pattern of writing to a pure log or accu"
},
{
"path": "lib/algae.ex",
"chars": 7198,
"preview": "defmodule Algae do\n @moduledoc \"\"\"\n Builder DSL to handle common ADT definition use cases\n \"\"\"\n\n import Algae.Intern"
},
{
"path": "mix.exs",
"chars": 1567,
"preview": "defmodule Algae.Mixfile do\n use Mix.Project\n\n def project do\n [\n app: :algae,\n aliases: aliases(),\n "
},
{
"path": "shell.nix",
"chars": 619,
"preview": "let\n nixpkgs = import (fetchTarball {\n # Run `cachix use jechol` to use compiled binary cache.\n url = \"https://gi"
},
{
"path": "test/algae_dsl_aliasing_test.exs",
"chars": 317,
"preview": "defmodule AlgaeDslAliasingTest.Base do\n import Algae\n\n alias __MODULE__\n\n defmodule A do\n defdata do\n a :: St"
},
{
"path": "test/algae_test.exs",
"chars": 1783,
"preview": "defmodule AlgaeTest do\n alias Example.{Animal, Book, Media, Wrapper}\n use ExUnit.Case\n\n doctest Algae, import: true\n "
},
{
"path": "test/support/example.ex",
"chars": 3393,
"preview": "import Algae\n\ndefmodule Example do\n @moduledoc false\n\n defdata Complex :: ([{:ok, integer()}] | number()) \\\\ 22\n\n def"
},
{
"path": "test/test_helper.exs",
"chars": 15,
"preview": "ExUnit.start()\n"
}
]
About this extraction
This page contains the full source code of the expede/algae GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 80 files (113.8 KB), approximately 34.0k tokens, and a symbol index with 124 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.