Created
January 28, 2015 06:36
-
-
Save markandrus/dd9b74bb75150e82747e to your computer and use it in GitHub Desktop.
example.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Option(object): | |
def __init__(self, is_defined, value=None): | |
self.is_defined = is_defined | |
if is_defined: | |
self.value = value | |
@classmethod | |
def Some(cls, value): | |
return Option(True, value) | |
@classmethod | |
def _None(cls): | |
return Option(False) | |
# Functor Interface | |
def map(self, func): | |
if self.is_defined: | |
return Option.Some(func(self.value)) | |
else: | |
return Option._None() | |
# Monad Interface | |
@classmethod | |
def _return(cls, value): | |
return Option(True, value) | |
def bind(self, func): | |
if self.is_defined: | |
return func(self.value) | |
else: | |
return Option._None() | |
class List(object): | |
def __init__(self, values): | |
self.values = values | |
# Functor Interface | |
def map(self, func): | |
new_values = [] | |
for value in self.values: | |
new_values.append(func(value)) | |
return List(new_values) | |
# Monad Interface | |
@classmethod | |
def _return(cls, value): | |
return List([value]) | |
def bind(self, func): | |
new_values = [] | |
for value in self.values: | |
new_values += func(value).values | |
return List(new_values) | |
class Function(object): | |
def __init__(self, func): | |
self.func = func | |
# Functor Interface | |
def map(self, func): | |
def new_func(value): | |
return func(self.func(value)) | |
return Function(new_func) | |
# Monad Interface | |
@classmethod | |
def _return(cls, value): | |
def constant_func(ignore): | |
return value | |
return Function(constant_func) | |
def bind(self, func): | |
# This one is harder to write. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment