Welcome to Hask3’s documentation!

This is a fork for the original project hask. We’re naming it hask3 because we’re intending this project to be used exclusively in Python 3.4+.

Most of the code of this project is still from the original authors.

Warning

Python 2.7 support is being dropped.

We officially support only Python 3.4+ (see the our Travis CI builds to get the full list of supported versions), even though the original project only supports Python 2.7.

We keep the code running in Python 2.7 as the baseline, but Python 2.7 is not supported and it may become broken at any time.

Overview

Hask3 is a pure-Python, zero-dependencies library that mimics most of the core language tools from Haskell, including:

  • Full Hindley-Milner type system (with typeclasses) that will typecheck any function decorated with a Hask type signature
  • Easy creation of new algebraic data types and new typeclasses, with Haskell-like syntax
  • Pattern matching with case expressions
  • Automagical function currying/partial application and function composition
  • Efficient, immutable, lazily evaluated List type with Haskell-style list comprehensions
  • All your favorite syntax and control flow tools, including operator sections, monadic error handling, guards, and more
  • Python port of (some of) the standard libraries from Haskell’s base, including:
    • Algebraic datatypes from the Haskell Prelude, including Maybe and Either
    • Typeclasses from the Haskell base libraries, including Functor, Applicative, Monad, Enum, Num, and all the rest
    • Standard library functions from base, including all functions from Prelude, Data.List, Data.Maybe, and more.

Features

The List type and list comprehensions

Hask provides the List type, a lazy and statically-typed list, similar to Haskell’s standard list type.

To create a new List, just put the elements inside L[ and ] brackets, or wrap an existing iterable inside L[ ]:

>>> from hask import L
>>> L[1, 2, 3]
L[1, 2, 3]
>>> my_list = ["a", "b", "c"]
>>> L[my_list]
L['a', 'b', 'c']
>>> L[(x**2 for x in range(1, 11))]
L[1 ...]

To add elements to the front of a List, use ^, the cons operator. To combine two lists, use +, the concatenation operator:

>>> 1 ^ L[2, 3]
L[1, 2, 3]
>>> "goodnight" ^ ("sweet" ^ ("prince" ^ L[[]]))
L['goodnight', 'sweet', 'prince']
>>> "a" ^ L[1.0, 10.3]  # doctests: +ELLIPSIS
Traceback (...)
...
TypeError: ...
>>> L[1, 2] + L[3, 4]
L[1, 2, 3, 4]

Lists are always evaluated lazily, and will only evaluate list elements as needed, so you can use infinite Lists or put never-ending generators inside of a List. (Of course, you can still blow up the interpreter if you try to evaluate the entirety of an infinite List, e.g. by trying to find the length of the List with len.)

One way to create infinite lists is via list comprehensions. As in Haskell, there are four basic type of list comprehensions:

>>> # list from 1 to infinity, counting by ones
>>> L[1 ...]


>>> # list from 1 to infinity, counting by twos
>>> L[1, 3, ...]

>>> # list from 1 to 20 (inclusive), counting by ones
>>> L[1, ..., 20]


>>> # list from 1 to 20 (inclusive), counting by fours
>>> L[1, 5, ..., 20]

List comprehensions can be used on ints, longs, floats, one-character strings, or any other instance of the Enum typeclass (more on this later).

Hask provides all of the Haskell functions for List manipulation (take(), drop(), takeWhile(), etc.), or you can also use Python-style indexing:

>>> from hask import L
>>> L[1, ...]
L[1 ...]
>>> from hask.Data.List import take
>>> take(5, L["a", "b", ...])
L['a', 'b', 'c', 'd', 'e']
>>> L[1,...][5:10]
L[6, 7, 8, 9, 10]
>>> from hask.Data.List import map
>>> from hask.Data.Char import chr
>>> letters = map(chr, L[97, ...])
>>> letters[:9]
L['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>> # DON'T do this: len(L[1, 3, ...])

Otherwise, you can use List just like you would use a regular Python list:

>>> from hask import L
>>> for i in L[0, ..., 3]:
...     print(i)
0
1
2
3
>>> 55 in L[1, 3, ...]
True

Algebraic Data Types

Hask allows you to define algebraic datatypes, which are immutable objects with a fixed number of typed, unnamed fields.

Here is the definition for the infamous Maybe type:

>>> from hask import data, d, deriving
>>> from hask import Read, Show, Eq, Ord
>>> Maybe, Nothing, Just =\
...     data.Maybe("a") == d.Nothing | d.Just("a") & \
...                        deriving(Read, Show, Eq, Ord)

Let’s break this down a bit. The syntax for defining a new type constructor is:

>>> data.TypeName("type param", "type param 2" ... "type param n")

This defines a new algebraic datatype with type parameters.

To define data constructors for this type, use d. The name of the data constructor goes first, followed by its fields. Multiple data constructors should be separated by |. If your data constructor has no fields, you can omit the parens. For example:

>>> FooBar, Foo, Bar =\
...    data.FooBar("a", "b") == d.Foo("a", "b", str) | d.Bar

To automagically derive typeclass instances for the type, add & deriving(...typeclasses...) after the data constructor declarations. Currently, the only typeclasses that can be derived are Eq, Show, Read, Ord, and Bounded.

Putting it all together, here are the definitions of Either and Ordering:

>>> from hask import Read, Show, Eq, Ord, Bounded
>>> Either, Left, Right =\
...    data.Either("a", "b") == d.Left("a") | d.Right("b") & deriving(Read, Show, Eq)
>>> Ordering, LT, EQ, GT =\
...     data.Ordering == d.LT | d.EQ | d.GT & deriving(Read, Show, Eq, Ord, Bounded)

You can now use the data constructors defined in a data statement to create instances of these new types. If the data constructor takes no arguments, you can use it just like a variable:

>>> Just(10)
Just(10)
>>> Nothing
Nothing
>>> Just(Just(10))
Just(Just(10))
>>> Left(1)
Left(1)
>>> Foo(1, 2, "hello")
Foo(1, 2, 'hello')

You can view the type of an object with _t() (equivalent to :t in ghci).

>>> from hask import _t, L
>>> _t(1)
'int'
>>> _t(Just("soylent green"))
'(Maybe str)'
>>> _t(Right(("a", 1)))
'(Either a (str, int))'
>>> _t(Just)
'(a -> (Maybe a))'
>>> _t(L[1, 2, 3, 4])
'[int]'

The type system and typed functions

So what’s up with those types? Hask operates its own shadow Hindley-Milner type system on top of Python’s type system; _t() shows the Hask type of a particular object.

In Hask, typed functions take the form of TypedFunc() objects, which are typed wrappers around Python functions. There are two ways to create TypedFunc objects:

  • Use the sig decorator to decorate the function with the type signature:

    @sig(H/ "a" >> "b" >> "a")
    def const(x, y):
        return x
    
  • Use the ** operator (similar to :: in Haskell) to provide the type.

    Useful for turning functions or lambdas into TypedFunc objects in the REPL, or wrapping already-defined Python functions:

    def const(x, y):
        return x
    
    const = const ** (H/ "a" >> "b" >> "a")
    

TypedFunc objects have several special properties. First, they are type checked – when arguments are supplied, the type inference engine will check whether their types match the type signature, and raise a TypeError if there is a discrepancy.

>>> from hask import H
>>> f = (lambda x, y: x + y) ** (H/ int >> int >> int)
>>> f(2, 3)
5
>>> f(9, 1.0)  
Traceback (...)
   ...
TypeError: ...

Second, TypedFunc objects can be partially applied:

>>> from hask import H
>>> g = (lambda a, b, c: a // (b + c)) ** (H/ int >> int >> int >> int)
>>> g(10, 2, 3)
2
>>> part_g = g(12)
>>> part_g(2, 2)
3
>>> g(20, 1)(4)
4

TypedFunc objects also have two special infix operators, the * and % operators. * is the compose operator (equivalent to . in Haskell), so f * g is equivalent to lambda x: f(g(x)). % is just the apply operator, which applies a TypedFunc to one argument (equivalent to $ in Haskell). The convinience of this notation (when combined with partial application) cannot be overstated – you can get rid of a ton of nested parenthesis this way:

>>> from hask.Prelude import flip
>>> h = (lambda x, y: x / y) ** (H/ float >> float >> float)
>>> h(3.0) * h(6.0) * flip(h, 2.0) % 36.0
9.0

The compose operation is also typed-checked, which makes it appealing to write programs in pointfree style, i.e. chaining together lots of functions with composition and relying on the type system to catch programming errors.

As you would expect, data constructors are also just TypedFunc objects:

>>> Just * Just * Just * Just % 77
Just(Just(Just(Just(77))))

The type signature syntax is very simple, and consists of a few basic primitives that can be combined to build any type signature:

  • Type literal for Python builtin type or user-defined class:

    int, float, set, list

  • Type variable:

    "a", "b", "zz"

  • List of some type:

    [int], ["a"], [["a"]]

  • Tuple type:

    (int, int), ("a", "b", "c"), (int, ("a", "b"))

  • ADT with type parameters:

    t(Maybe, "a"), t(Either, "a", str)

  • Unit type (None):

    None

  • Untyped Python function:

    func

  • Typeclass constraint:

    H[(Eq, "a"), (Show, "b")]/, H[(Functor, "f"), (Show, "f")]/

Some examples:

# add two ints together
@sig(H/ int >> int >> int)
def add(x, y):
    return x + y


# reverse order of arguments to a function
@sig(H/ (H/ "a" >> "b" >> "c") >> "b" >> "a" >> "c")
def flip(f, b, a):
    return f(a, b)


# map a Python (untyped) function over a Python (untyped) set
@sig(H/ func >> set >> set)
def set_map(fn, lst):
    return set((fn(x) for x in lst))


# map a typed function over a List
@sig(H/ (H/ "a" >> "b") >> ["a"] >> ["b"])
def map(f, xs):
    return L[(f(x) for x in xs)]


# type signature with an Eq constraint
@sig(H[(Eq, "a")]/ "a" >> ["a"] >> bool)
def not_in(y, xs):
    return not any((x == y for x in xs))


# type signature with a type constructor (Maybe) that has type arguments
@sig(H/ int >> int >> t(Maybe, int))
def safe_div(x, y):
    return Nothing if y == 0 else Just(x/y)


# type signature for a function that returns nothing
@sig(H/ int >> None)
def launch_missiles(num_missiles):
    print("Launching {0} missiles! Bombs away!" % num_missiles)

It is also possible to create type synonyms using t(). For example, check out the definition of Rational:

Ratio, R =\
        data.Ratio("a") == d.R("a", "a") & deriving(Eq)


Rational = t(Ratio, int)


@sig(H/ Rational >> Rational >> Rational)
def addRational(rat1, rat2):
    ...

Pattern matching

Pattern matching is a more powerful control flow tool than the if statement, and can be used to deconstruct iterables and ADTs and bind values to local variables.

Pattern matching expressions follow this syntax:

~(caseof(value_to_match)
    | m(pattern_1) >> return_value_1
    | m(pattern_2) >> return_value_2
    | m(pattern_3) >> return_value_3)

Here is a function that uses pattern matching to compute the fibonacci sequence. Note that within a pattern match expression, m.* is used to bind variables, and p.* is used to access them:

>>> from hask import caseof, m, p, sig, H
>>> @sig(H/ int >> int)
... def fib(x):
...     return ~(caseof(x)
...                 | m(0)   >> 1
...                 | m(1)   >> 1
...                 | m(m.n) >> fib(p.n - 2) + fib(p.n - 1))
>>> fib(1)
1
>>> fib(6)
13

As the above example shows, you can combine pattern matching and recursive functions without a hitch.

You can also deconstruct an iterable using ^ (the cons operator). The variable before the ^ is bound to the first element of the iterable, and the variable after the ^ is bound to the rest of the iterable. Here is a function that adds the first two elements of any iterable, returning Nothing if there are less than two elements:

>>> from hask import sig, t, caseof, m, p, H
>>> from hask import Num, Maybe, Just, Nothing
>>> @sig(H[(Num, "a")]/ ["a"] >> t(Maybe, "a"))
... def add_first_two(xs):
...     return ~(caseof(xs)
...                 | m(m.x ^ (m.y ^ m.z)) >> Just(p.x + p.y)
...                 | m(m.x)               >> Nothing)
>>> add_first_two(L[1, 2, 3, 4, 5])
Just(3)
>>> add_first_two(L[9.0])
Nothing

Pattern matching is also very useful for deconstructing ADTs and assigning their fields to temporary variables.

>>> from hask import caseof, m, p
>>> from hask import Num, Maybe, Just, Nothing
>>> def default_to_zero(x):
...     return ~(caseof(x)
...                 | m(Just(m.x)) >> p.x
...                 | m(Nothing)   >> 0)
>>> default_to_zero(Just(27))
27
>>> default_to_zero(Nothing)
0

If you find pattern matching on ADTs too cumbersome, you can also use numeric indexing on ADT fields. An IndexError will be thrown if you mess something up.

>>> Just(20.0)[0]
20.0
>>> Left("words words words words")[0]
'words words words words'
>>> Nothing[0]  # IndexError

Typeclasses and typeclass instances

Typeclasses allow you to add additional functionality to your ADTs. Hask implements all of the major typeclasses from Haskell (see the Appendix for a full list) and provides syntax for creating new typeclass instances.

As an example, let’s add a Monad instance for the Maybe type. First, however, Maybe needs Functor and Applicative instances.

def maybe_fmap(fn, x):
    """Apply a function to the value inside of a (Maybe a) value"""
    return ~(caseof(x)
                | m(Nothing)   >> Nothing
                | m(Just(m.x)) >> Just(fn(p.x)))


instance(Functor, Maybe).where(
    fmap = maybe_fmap
)

Maybe is now an instance of Functor. This allows us to call fmap and map any function of type a -> b into a value of type Maybe a.

>>> times2 = (lambda x: x * 2) ** (H/ int >> int)
>>> toFloat = float ** (H/ int >> float)
>>> fmap(toFloat, Just(10))
Just(10.0)
>>> fmap(toFloat, fmap(times2, Just(25)))
Just(50.0)

Lots of nested calls to fmap get unwieldy very fast. Fortunately, any instance of Functor can be used with the infix fmap operator, *. This is equivalent to <$> in Haskell. Rewriting our example from above:

>>> (toFloat * times2) * Just(25)
Just(50.0)
>>> (toFloat * times2) * Nothing
Nothing

Note that this example uses * as both the function compose operator and as fmap, to lift functions into a Maybe value. If this seems confusing, remember that fmap for functions is just function composition!

Now that Maybe is an instance of Functor, we can make it an instance of Applicative and then an instance of Monad by defining the appropriate function implementations. To implement Applicative, we just need to provide pure. To implement Monad, we need to provide bind.

>>> from hask import Applicative, Monad
>>> instance(Applicative, Maybe).where(
...    pure = Just
... )
>>> instance(Monad, Maybe).where(
...     bind = lambda x, f: ~(caseof(x)
...                             | m(Just(m.a)) >> f(p.a)
...                             | m(Nothing)   >> Nothing)
... )

The bind function also has an infix form, which is >> in Hask.

>>> @sig(H/ int >> int >> t(Maybe, int))
... def safe_div(x, y):
...     return Nothing if y == 0 else Just(x/y)
>>> from hask.Prelude import flip
>>> divBy = flip(safe_div)
>>> Just(9) >> divBy(3)
Just(3)
>>> Just(12) >> divBy(2) >> divBy(2) >> divBy(3)
Just(1)
>>> Just(12) >> divBy(0) >> divBy(6)
Nothing

As in Haskell, List is also a monad, and bind for the List type is just concatMap.

>>> from hask.Data.List import replicate
>>> L[1, 2] >> replicate(2) >> replicate(2)
L[1, 1, 1, 1, 2, 2, 2, 2]

You can also define typeclass instances for classes that are not ADTs:

>>> class Person(object):
...     def __init__(self, name, age):
...         self.name = name
...         self.age = age
>>> instance(Eq, Person).where(
...     eq = lambda p1, p2: p1.name == p2.name and p1.age == p2.age
... )
>>> Person("Philip Wadler", 59) == Person("Simon Peyton Jones", 57)
False

If you want instances of the Show, Eq, Read, Ord, and Bounded typeclasses for your ADTs, it is adviseable to use deriving to automagically generate instances rather than defining them manually.

Defining your own typeclasses is pretty easy–take a look at Typeclass and look at the typeclasses defined in hask.Data.Functor and hask.Data.Num to see how it’s done.

Operator sections

Hask also supports operator sections (e.g. (1+) in Haskell). Sections are just TypedFunc objects, so they are automagically curried and typechecked.

>>> from hask import __
>>> f = (__ - 20) * (2 ** __) * (__ + 3)
>>> f(10)
8172
>>> ((90/__) * (10+__)) * Just(20)
Just(3)
>>> from hask.Data.List import takeWhile
>>> takeWhile(__<5, L[1, ...])
L[1, 2, 3, 4]
>>> (__+__)('Hello ', 'world')
'Hello world'
>>> (__**__)(2)(10)
1024
>>> from hask.Data.List import zipWith, take
>>> take(5) % zipWith(__ * __, L[1, ...], L[1, ...])
L[1, 4, 9, 16, 25]

As you can see, this much easier than using lambda and adding a type signature with the (lambda x: ...) ** (H/ ...) syntax.

In addition, the types of the TypedFuncs created by sections are always polymorphic, to allow for any operator overloading.

Note that if you are using IPython, Hask’s __ will conflict with IPython’s special double underscore variable. To avoid conflicts, you can use from hask import __ as _s in IPython.

Guards

If you don’t need the full power of pattern matching and just want a neater switch statement, you can use guards. The syntax for guards is almost identical to the syntax for pattern matching.

::
~(guard(expr_to_test)
c(test_1) >> return_value_1
c(test_2) >> return_value_2
otherwise >> return_value_3

)

As in Haskell, `~hask.lang.syntax.otherwise`:object: will always evaluate to True and can be used as a catch-all in guard expressions. If no match is found (and an otherwise clause is not present), a NoGuardMatchException will be raised.

Guards will also play nicely with sections:

>>> from hask import guard, c, otherwise
>>> porridge_tempurature = 80
>>> ~(guard(porridge_tempurature)
...     | c(__ < 20)  >> "Porridge is too cold!"
...     | c(__ < 90)  >> "Porridge is just right!"
...     | c(__ < 150) >> "Porridge is too hot!"
...     | otherwise   >> "Porridge has gone thermonuclear"
... )
'Porridge is just right!'

If you need a more complex conditional, you can always use lambdas, regular Python functions, or any other callable in your guard condition.

>>> def examine_password_security(password):
...     analysis = ~(guard(password)
...         | c(lambda x: len(x) > 20) >> "Wow, that's one secure password"
...         | c(lambda x: len(x) < 5)  >> "You made Bruce Schneier cry"
...         | c(__ == "12345")         >> "Same combination as my luggage!"
...         | otherwise                >> "Hope it's not 'password'"
...     )
...     return analysis
>>> nuclear_launch_code = "12345"
>>> examine_password_security(nuclear_launch_code)
'Same combination as my luggage!'

Monadic error handling (of Python functions)

If you want to use Maybe and Either to handle errors raised by Python functions defined outside Hask, you can use the decorators in_maybe and in_either to create functions that call the original function and return the result wrapped inside a Maybe or Either value.

If a function wrapped in in_maybe raises an exception, the wrapped function will return Nothing. Otherwise, the result will be returned wrapped in a Just.

>>> def eat_cheese(cheese):
...     if cheese <= 0:
...         raise ValueError("Out of cheese error")
...     return cheese - 1
>>> maybe_eat = in_maybe(eat_cheese)
>>> maybe_eat(1)
Just(0)
>>> maybe_eat(0)
Nothing

Note that this is equivalent to lifting the original function into the Maybe monad. That is, its type has changed from func to a -> Maybe b. This makes it easier to use the convineient monad error handling style commonly seen in Haskell with existing Python functions.

Continuing with this silly example, let’s try to eat three pieces of cheese, returning Nothing if the attempt was unsuccessful:

>>> cheese = 10
>>> cheese_left = Just(cheese) >> maybe_eat >> maybe_eat >> maybe_eat
>>> cheese_left
Just(7)
>>> cheese = 1
>>> cheese_left = Just(cheese) >> maybe_eat >> maybe_eat >> maybe_eat
>>> cheese_left
Nothing

Notice that we have taken a regular Python function that throws Exceptions, and are now handling it in a type-safe, monadic way.

The in_either function works just like in_maybe. If an Exception is thrown, the wrapped function will return the exception wrapped in Left. Otherwise, the result will be returned wrapped in Right.

>>> either_eat = in_either(eat_cheese)
>>> either_eat(Right(10))
Right(9)
>>> either_eat(Right(0))
Left(ValueError('Out of cheese error',))

Chained cheese-eating in the Either monad is left as an exercise for the reader.

You can also use in_maybe or in_either as decorators:

@in_maybe
def some_function(x, y):
    ...

hask – Hask API

hask.lang.hindley_milner – Hindley-Milner type-checking and inference

Implementation of Hindley-Milner type inference system for Python, based on Robert Smallshire’s implementation for OWL BASIC.

Robert’s original version can be found here: http://smallshire.org.uk/sufficientlysmall/2010/04/11/a-hindley-milner-type-inference-implementation-in-python/

Changes from Robert’s version:

  1. Simplified type language somewhat (Let and Letrec are merged, as are Var and Ident)
  2. Type system expanded to handle polymorphic higher-kinded types (however, in its current state it does not do this correctly due to the way that typeclasses were bolted on; this will be fixed in future versions)
  3. Interface tweaked a bit to work better with Python types, including pretty-printing of type names and some useful subclasses of TypeOperator
  4. Type unification also unifies typeclass constraints
class hask.lang.hindley_milner.AST[source]

A low-level AST node in a typed lambda calculus.

class hask.lang.hindley_milner.App(fn, arg)[source]

Function application.

An App node represents the application of a single argument. Functions over several arguments are curried.

class hask.lang.hindley_milner.Function(from_type, to_type)[source]

A binary type constructor which builds function types

class hask.lang.hindley_milner.Lam(v, body)[source]

Lambda abstraction

class hask.lang.hindley_milner.Let(v, defn, body)[source]

Let binding (always recursive)

class hask.lang.hindley_milner.ListType(list_type)[source]

Unary constructor which builds list types

class hask.lang.hindley_milner.Tuple(types)[source]

N-ary constructor which builds tuple types

class hask.lang.hindley_milner.TypeOperator(name, types)[source]

An n-ary type constructor which builds a new type from old

class hask.lang.hindley_milner.TypeVariable(constraints=())[source]

A type variable standing for an arbitrary type.

All type variables have a unique id, but names are only assigned lazily, when required.

Note that this approach is not thread-safe.

name

Names are allocated to TypeVariables lazily, so that only TypeVariables converted to strings are given names.

class hask.lang.hindley_milner.Var(name)[source]

Variable/Identifier

hask.lang.hindley_milner.analyze(node, env, non_generic=None)[source]

Computes the type of the expression given by node.

The type of the node is computed in the context of the supplied type environment, env. Data types can be introduced into the language simply by having a predefined set of identifiers in the initial environment. This way there is no need to change the syntax or, more importantly, the type-checking program when extending the language.

Parameters:
  • node – The root of the abstract syntax tree.
  • env – The type environment is a mapping of expression identifier names to type assignments. to type assignments.
  • non_generic – A set of non-generic variables, or None
Returns:

The computed type of the expression.

Raises:

TypeError – The type of the expression could not be inferred, for example if it is not possible to unify two types such as Integer and Bool or if the abstract syntax tree rooted at node could not be parsed

hask.lang.hindley_milner.fresh(t, non_generic)[source]

Makes a copy of a type expression.

The type t is copied. The the generic variables are duplicated and the non_generic variables are shared.

Parameters:
  • t – A type to be copied.
  • non_generic – A set of non-generic TypeVariables
hask.lang.hindley_milner.getType(name, env, non_generic)[source]

Get the type of identifier name from the type environment env.

Parameters:
  • name – The identifier name
  • env – The type environment mapping from identifier names to types
  • non_generic – A set of non-generic TypeVariables
Raises:

ParseError – Raised if name is an undefined symbol in the type environment.

hask.lang.hindley_milner.isGeneric(v, non_generic)[source]

Checks whether a given variable occurs in a list of non-generic variables

Note that a variables in such a list may be instantiated to a type term, in which case the variables contained in the type term are considered non-generic.

Note

Must be called with v pre-pruned

Parameters:
  • v – The TypeVariable to be tested for genericity
  • non_generic – A set of non-generic TypeVariables
Returns:

True if v is a generic variable, otherwise False

hask.lang.hindley_milner.occursIn(t, types)[source]

Checks whether a types variable occurs in any other types.

Parameters:
  • v – The TypeVariable to be tested for
  • types – The sequence of types in which to search
Returns:

True if t occurs in any of types, otherwise False

hask.lang.hindley_milner.occursInType(v, type2)[source]

Checks whether a type variable occurs in a type expression.

Note

Must be called with v pre-pruned

Parameters:
  • v – The TypeVariable to be tested for
  • type2 – The type in which to search
Returns:

True if v occurs in type2, otherwise False

hask.lang.hindley_milner.prune(t)[source]

Returns the currently defining instance of t.

As a side effect, collapses the list of type instances. The function prune is used whenever a type expression has to be inspected: it will always return a type expression which is either an uninstantiated type variable or a type operator; i.e. it will skip instantiated variables, and will actually prune them from expressions to remove long chains of instantiated variables.

Parameters:t – The type to be pruned
Returns:An uninstantiated TypeVariable or a TypeOperator
hask.lang.hindley_milner.show_type(type_name)[source]

Pretty-print a Python type or internal type name.

Parameters:type_name – a Python type, or a string representing a type name
Returns:a string representation of the type
hask.lang.hindley_milner.unify(t1, t2)[source]

Unify the two types t1 and t2. Makes the types t1 and t2 the same.

Note that the current method of unifying higher-kinded types does not properly handle kind, i.e. it will happily unify f a and g b c. This is due to the way that typeclasses are implemented, and will be fixed in future versions.

Parameters:
  • t1 – The first type to be made equivalent
  • t2 – The second type to be be equivalent

Modify t1 and t2 in-place, by modifying their constraints for the unification.

Raises:TypeError – Raised if the types cannot be unified.
hask.lang.hindley_milner.unify_var(v1, t2)[source]

Unify the type variable v1 and the type t2, i.e. makes their types the same and unifies typeclass constraints. Note: Must be called with v1 and t2 pre-pruned

Parameters:
  • v1 – The type variable to be made equivalent
  • t2 – The second type to be be equivalent

Instead of returning, modify v1 and t2 to add the unification as a constraint.

Raises:TypeError – Raised if the types cannot be unified.

hask.lang.lazylist – A lazy List

class hask.lang.lazylist.Enum[source]

Class Enum defines operations on sequentially ordered types.

The enumFrom… methods are used in translation of arithmetic sequences.

Instances of Enum may be derived for any enumeration type (types whose constructors have no fields). The nullary constructors are assumed to be numbered left-to-right by fromEnum from 0 through n-1.

Attributes:

  • toEnum
  • fromEnum
  • succ
  • pred
  • enumFrom
  • enumFromThen
  • enumFrom
  • enumFromThenTo
  • EnumFromTo

Minimal complete definition:

  • toEnum
  • fromEnum
L

L is the syntactic construct for Haskell-style list comprehensions and lazy list creation. To create a new List, just wrap an interable in L[ ].

List comprehensions can be used with any instance of Enum, including the built-in types int, long (in Python 2), float, and str (a char).

There are four basic list comprehension patterns:

>>> from hask.lang import L
>>> # list from 1 to infinity, counting by ones
>>> L[1, ...]
L[1, ...]
>>> # list from 1 to infinity, counting by twos
>>> L[1, 3, ...]
L[1, 3, ...]
>>> # list from 1 to 20 (inclusive), counting by ones
>>> L[1, ..., 20]
L[1, ..., 20]
>>> # list from 1 to 20 (inclusive), counting by fours
>>> L[1, 5, ..., 20]
L[1, 5, ..., 20]
class hask.lang.lazylist.List(head=None, tail=None)[source]

Statically typed lazy sequence datatype.

See L for more information.

hask.lang.syntax – The “syntactic” elements to build Hask programs

class hask.lang.syntax.sig(signature)[source]

Decorator to convert a Python function into a statically typed function (TypedFunc object).

TypedFuncs are automagically curried, and polymorphic type arguments will be inferred by the type system.

Usage:

@sig(H/ int >> int >> int )
def add(x, y):
    return x + y

@sig(H[(Show, "a")]/ >> "a" >> str)
def to_str(x):
    return str(x)
H
class hask.lang.syntax.__constraints__(constraints=None)[source]

H/ creates a new function type signature.

Examples:

(H/ int >> int >> int)
(H/ (H/ "a" >> "b" >> "c") >> "b" >> "a" >> "c")
(H/ func >> set >> set)
(H/ (H/ "a" >> "b") >> ["a"] >> ["b"])
(H[(Eq, "a")]/ "a" >> ["a"] >> bool)
(H/ int >> int >> t(Maybe, int))
(H/ int >> None)

See sig for more information on type signature decorators.

class hask.lang.syntax.Syntax(err_msg)[source]

Base class for new syntactic constructs. All of the new “syntax” elements of Hask inherit from this class.

By default, a piece of syntax will raise a syntax error with a standard error message if the syntax object is used with a Python builtin operator.

Subclasses may override these methods to define what syntax is valid for those objects.

class hask.lang.syntax.instance(typecls, cls)[source]

Special syntax for defining typeclass instances.

Example usage:

instance(Functor, Maybe).where(
    fmap = ...
)
class hask.lang.syntax.caseof(value)[source]

Pattern matching can be used to deconstruct lists and ADTs, and is a very useful control flow tool.

Usage:

~(caseof(value_to_match)
    | m(pattern_1) >> return_value_1
    | m(pattern_2) >> return_value_2
    | m(pattern_3) >> return_value_3)

Example usage:

@sig(H/ int >> int)
def fib(x):
    return ~(caseof(x)
                | m(0)   >> 1
                | m(1)   >> 1
                | m(m.n) >> fib(p.n - 1) + fib(p.n - 2))
data
class hask.lang.syntax.__data__[source]

data is part of Hask’s special syntax for defining ADTs.

Example usage:

>>> from hask import data, d, deriving, Read, Show, Eq, Ord
>>> Maybe, Nothing, Just =\
...     data.Maybe("a") == d.Nothing | d.Just("a") & \
...     deriving(Read, Show, Eq, Ord)
d
class hask.lang.syntax.__d__[source]

d is part of hask’s special syntax for defining algebraic data types.

See data for more information.

class hask.lang.syntax.deriving(*tclasses)[source]

deriving is part of hask’s special syntax for defining algebraic data types.

See data for more information.

hask.lang.syntax.t(type_constructor, *params)[source]

Helper to instantiate TypeSignatureHKT.

hask.lang.syntax.typify(fn, hkt=None)[source]

Convert an untyped Python function to a TypeFunc.

Parameters:
  • fn – The function to wrap
  • hkt – A higher-kinded type wrapped in a closure (e.g., lambda x: t(Maybe, x))
Returns:

A TypedFunc object with a polymorphic type (e.g. a -> b -> c, etc) with the same number of arguments as fn. If hkt is supplied, the return type will be the supplied HKT parameterized by a type variable.

Example usage:

@typify(hkt=lambda x: t(Maybe, x))
def add(x, y):
    return x + y
undefined
class hask.lang.syntax.__undefined__[source]

Undefined value with special syntactic powers. Whenever you try to use one if its magic methods, it returns undefined. Used to prevent overzealous evaluation in pattern matching.

Its type unifies with any other type.

class hask.lang.syntax.guard(value)[source]

Special syntax for guard expression.

Usage:

~(guard(<expr to test>)
    | c(<test_fn_1>) >> <return_value_1>
    | c(<test_fn_2>) >> <return_value_2>
    | otherwise      >> <return_value_3>
)

Examples:

~(guard(8)
     | c(lambda x: x < 5) >> "less than 5"
     | c(lambda x: x < 9) >> "less than 9"
     | otherwise          >> "unsure"
)

# Using guards with sections. See help(__) for information on sections.
~(guard(20)
    | c(__ > 10)  >> 20
    | c(__ == 10) >> 10
    | c(__ > 5)   >> 5
    | otherwise   >> 0)
Parameters:value – the value being tested in the guard expression
Returns:the return value corresponding to the first matching condition
Raises:NoGuardMatchException (if no match is found)
c
class hask.lang.syntax.__guard_test__(fn)[source]

A case in a guard.

c creates a new condition that can be used in a guard expression.

otherwise is a guard condition that always evaluates to True.

Usage:

~(guard(<expr to test>)
    | c(<test_fn_1>) >> <return_value_1>
    | c(<test_fn_2>) >> <return_value_2>
    | otherwise      >> <return_value_3>
)

See guard for more details.

otherwise

A c object that evaluates to True.

p
class hask.lang.syntax.__var_access__(err_msg)[source]

p.* accesses a local variable bound during pattern matching.

For example usage, see caseof.

m
class hask.lang.syntax.__var_bind__(err_msg)[source]

m.* binds a local variable while pattern matching.

For example usage, see caseof.

hask.lang.syntax._t(obj)[source]

Returns a string representing the type of an object, including higher-kinded types and ADTs.

Equivalent to :t in Haskell. Meant to be used in the REPL, but might also be useful for debugging.

Parameters:obj – the object to inspect
Returns:A string representation of the type

Usage:

>>> from hask import _t
>>> _t(1)
'int'
>>> _t(Just("hello world"))
'(Maybe str)'
hask.lang.syntax._i(obj)[source]

Show information about an object.

Equivalent to :i in Haskell or help(obj) in Python. Should only be used in the REPL.

Parameters:obj – the object to inspect

Usage:

>>> _i(Just("hello world"))
...

>>> _i(Either)
...
__
class hask.lang.syntax.__section__(syntax_err_msg)[source]

The class of the __ object.

This is Hask’s special syntax for operator sections: a placeholder for arguments (operands).

Example usage:

>>> from __future__ import division
>>> from hask.lang import __
>>> (__+1)(5)
6
>>> (6//__) * (__-1) % 4
2
>>> (__**__)(2, 10)
1024

Operators supported:

+ - * / // ** >> << | & ^ == != > >= < <=
exception hask.lang.syntax.IncompletePatternError[source]
class hask.lang.syntax.MatchStackFrame(value)[source]

One stack frame for pattern matching bound variable stack

class hask.lang.syntax.MatchStack[source]

Stack for storing locally bound variables from matches

hask.lang.type_system – The implementation of the type system

class hask.lang.type_system.Hask[source]

Base class for objects within hask.

ADTs, TypedFunc, List, Undefined, and other hask-related types are all subclasses of Hask.

All subclasses must define __type__, which returns a representation of the object in the internal type system language.

class hask.lang.type_system.Undefined[source]

A class with no concrete type definition (so its type can unify with any other type). Used to create undefined and to enable psuedo-laziness in pattern matching.

class hask.lang.type_system.PyFunc[source]

Singleton object that represents (any of the) Python function types in the type system and in type signatures.

hask.lang.type_system.typeof(obj)[source]

Returns the type of an object within the internal type system.

Parameters:obj – the object to inspect
Returns:An object representing the type in the internal type system language (i.e., a TypeOperator or TypeVariable).
class hask.lang.type_system.TypeSignature(args, constraints)[source]

Internal representation of a type signature, consisting of a list of function type arguments and a list of (typeclass, type_variable) typeclass constraint pairs.

class hask.lang.type_system.TypeSignatureHKT(tcon, params)[source]

Internal representation of a higher-kinded type within a type signature, consisting of the type constructor and its type parameter names.

exception hask.lang.type_system.TypeSignatureError[source]
class hask.lang.type_system.TypedFunc(fn, fn_args, fn_type)[source]

Partially applied, statically typed function wrapper.

class hask.lang.type_system.ADT[source]

Base class for Hask algebraic data types.

hask.lang.typeclasses – The standard type classes

class hask.lang.typeclasses.Show[source]

Conversion of values to readable strings.

Attributes:

  • __str__
  • show

Minimal complete definition:

  • show
class hask.lang.typeclasses.Eq[source]

The Eq class defines equality (==) and inequality (!=).

Attributes:

  • __eq__
  • __ne__

Minimal complete definition:

  • eq
class hask.lang.typeclasses.Bounded[source]

The Bounded class is used to name the upper and lower limits of a type. Ord is not a superclass of Bounded since types that are not totally ordered may also have upper and lower bounds.

The Bounded class may be derived for any enumeration type; minBound is the first constructor listed in the data declaration and maxBound is the last. Bounded may also be derived for single-constructor datatypes whose constituent types are in Bounded.

Attributes:

  • minBound
  • maxBound

Minimal complete definition:

  • minBound
  • maxBound
class hask.lang.typeclasses.Ord[source]

The Ord class is used for totally ordered datatypes.

Instances of Ord can be derived for any user-defined datatype whose constituent types are in Ord. The declared order of the constructors in the data declaration determines the ordering in derived Ord instances. The Ordering datatype allows a single comparison to determine the precise ordering of two objects.

Dependencies:

Attributes:

  • __lt__
  • __le__
  • __gt__
  • __ge__

Minimal complete definition:

  • lt
class hask.lang.typeclasses.Read[source]

Parsing of Strings, producing values.

Attributes:

  • read

Minimal complete definition:

  • read

hask.Control.Applicative – The Applicative type class

class hask.Control.Applicative.Applicative[source]

A functor with application, providing operations to embed pure expressions (pure), and sequence computations and combine their results (ap).

Dependencies:

Attributes:

  • pure

Minimal complete definition:

  • pure

hask.Control.Monad – The Monad type class

class hask.Control.Monad.Monad[source]

The Monad class defines the basic operations over a monad, a concept from a branch of mathematics known as category theory. From the perspective of a Haskell programmer, however, it is best to think of a monad as an abstract datatype of actions.

Dependencies:

Attributes:

  • bind
  • __rshift__

Minimal complete definition:

  • bind

hask.Data.Char – The Data.Char

hask.Data.Char.isControl(*args, **kwargs)

isControl :: str -> bool

Selects control characters, which are the non-printing characters of the Latin-1 subset of Unicode.

hask.Data.Char.isSpace(*args, **kwargs)

isSpace :: str -> bool

Returns True for any Unicode space character, and the control characters t, n, r, f, v.

hask.Data.Char.isLower(*args, **kwargs)

isLower :: str -> bool

Selects lower-case alphabetic Unicode characters (letters).

hask.Data.Char.isUpper(*args, **kwargs)

isUpper :: str -> bool

Selects upper-case or title-case alphabetic Unicode characters (letters). Title case is used by a small number of letter ligatures like the single-character form of Lj.

hask.Data.Char.isAlpha(*args, **kwargs)

isAlpha :: str -> bool

Selects alphabetic Unicode characters (lower-case, upper-case and title-case letters, plus letters of caseless scripts and modifiers letters). This function is equivalent to isLetter.

hask.Data.Char.isAlphaNum(*args, **kwargs)

isAlphaNum :: str -> bool

Selects alphabetic or numeric digit Unicode characters.

Note that numeric digits outside the ASCII range are selected by this function but not by isDigit. Such digits may be part of identifiers but are not used by the printer and reader to represent numbers.

hask.Data.Char.isPrint(*args, **kwargs)

isPrint :: str -> bool

Selects printable Unicode characters (letters, numbers, marks, punctuation, symbols and spaces).

hask.Data.Char.isDigit(*args, **kwargs)

isDigit :: str -> bool

Selects ASCII digits, i.e. ‘0’..‘9’.

hask.Data.Char.isOctDigit(*args, **kwargs)

isOctDigit :: str -> bool

Selects ASCII octal digits, i.e. ‘0’..‘7’.

hask.Data.Char.isHexDigit(*args, **kwargs)

isHexDigit :: str -> bool

Selects ASCII hexadecimal digits, i.e. ‘0’..‘9’, ‘a’..’f’, ‘A’..’F’.

hask.Data.Char.isLetter(*args, **kwargs)

isLetter :: str -> bool

Selects alphabetic Unicode characters (lower-case, upper-case and title-case letters, plus letters of caseless scripts and modifiers letters). This function is equivalent to isAlpha.

hask.Data.Char.isMark(*args, **kwargs)

isMark :: str -> bool

Selects Unicode mark characters, e.g. accents and the like, which combine with preceding letters.

hask.Data.Char.isNumber(*args, **kwargs)

isNumber :: str -> bool

Selects Unicode numeric characters, including digits from various scripts, Roman numerals, etc.

hask.Data.Char.isPunctuation(*args, **kwargs)

isPunctuation :: str -> bool

Selects Unicode punctuation characters, including various kinds of connectors, brackets and quotes.

hask.Data.Char.isSymbol(*args, **kwargs)

isSymbol :: str -> bool

Selects Unicode symbol characters, including mathematical and currency symbols.

hask.Data.Char.isSeparator(*args, **kwargs)

isSeparator :: str -> bool

Selects Unicode space and separator characters.

hask.Data.Char.isAscii(*args, **kwargs)

isAscii :: str -> bool

Selects the first 128 characters of the Unicode character set, corresponding to the ASCII character set.

hask.Data.Char.isLatin1(*args, **kwargs)

isLatin1 :: str -> bool

Selects the first 256 characters of the Unicode character set, corresponding to the ISO 8859-1 (Latin-1) character set.

hask.Data.Char.isAsciiUpper(*args, **kwargs)

isAsciiUpper :: str -> bool

Selects ASCII upper-case letters, i.e. characters satisfying both isAscii and isUpper.

hask.Data.Char.isAsciiLower(*args, **kwargs)

isAsciiLower :: str -> bool

Selects ASCII lower-case letters, i.e. characters satisfying both isAscii and isLower.

hask.Data.Char.toLower(*args, **kwargs)

toLower :: str -> str

Convert a letter to the corresponding lower-case letter, if any. Any other character is returned unchanged.

hask.Data.Char.toUpper(*args, **kwargs)

toUpper :: str -> str

Convert a letter to the corresponding upper-case letter, if any. Any other character is returned unchanged.

hask.Data.Char.toTitle(*args, **kwargs)

toTitle :: str -> str

Convert a letter to the corresponding title-case or upper-case letter, if any. (Title case differs from upper case only for a small number of ligature letters.) Any other character is returned unchanged.

hask.Data.Char.digitToInt(*args, **kwargs)

digitToInt :: str -> int

Convert a single digit Char to the corresponding Int. This function fails unless its argument satisfies isHexDigit, but recognises both upper and lower-case hexadecimal digits (i.e. ‘0’..‘9’, ‘a’..’f’, ‘A’..’F’).

hask.Data.Char.intToDigit(*args, **kwargs)

intToDigit :: int -> str

Convert an Int in the range 0..15 to the corresponding single digit Char. This function fails on other inputs, and generates lower-case hexadecimal digits.

hask.Data.Char.chr(x)

The builtin chr converted to a TypedFunc. Defined as chr ** (H/ int >> str)

hask.Data.Char.ord(x)

The builtin ord converted to a TypedFunc. Defined as ord ** (H/ int >> str)

hask.Data.Either – The Data.Either

hask.Data.Either.Either

The ADT Either:

data.Either == d.Left('a') | d.Right('b') & deriving(Read, Show, Eq, Ord)
hask.Data.Either.Left(a)
hask.Data.Either.Right(b)
hask.Data.Either.either(*args, **kwargs)

either :: (a -> c) -> (b -> c) -> Either a b -> c

Case analysis for the Either type. If the value is Left(a), apply the first function to a; if it is Right(b), apply the second function to b.

hask.Data.Either.in_either(fn)[source]

Decorator for monadic error handling. If the decorated function raises an exception, return the exception inside Left. Otherwise, take the result and wrap it in Right.

hask.Data.Either.lefts(*args, **kwargs)

lefts :: [Either a b] -> [a]

Extracts from a List of Either all the Left elements. All the Left elements are extracted in order.

hask.Data.Either.rights(*args, **kwargs)

rights :: [Either a b] -> [b]

Extracts from a list of Either all the Right elements. All the Right elements are extracted in order.

hask.Data.Either.isLeft(*args, **kwargs)

isLeft :: Either a b -> bool

Return True if the given value is a Left-value, False otherwise.

hask.Data.Either.isRight(*args, **kwargs)

isRight :: Either a b -> bool

Return True if the given value is a Right-value, False otherwise.

hask.Data.Either.partitionEithers(*args, **kwargs)

partitionEithers :: [Either a b] -> ([a], [b])

Partitions a List of Either into two lists. All the Left elements are extracted, in order, to the first component of the output. Similarly the Right elements are extracted to the second component of the output.

hask.Data.Eq – The Data.Eq

Reexport the hask.lang.typeclasses.Eq.

hask.Data.Foldable – The Data.Foldable

class hask.Data.Foldable.Foldable[source]

Data structures that can be folded.

Attributes:

  • foldr
  • foldr1
  • foldl
  • foldl_
  • foldl1
  • toList
  • null
  • length
  • elem
  • maximum
  • minimum
  • sum
  • product

Minimal complete definition:

  • foldr

Magic methods:

  • __iter__
hask.Data.Foldable.foldr(*args, **kwargs)

foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b

Right-associative fold of a structure.

hask.Data.Foldable.foldr1(*args, **kwargs)

foldr1 :: Foldable t => (a -> a -> a) -> t a -> a

A variant of foldr that has no base case, and thus may only be applied to non-empty structures.

hask.Data.Foldable.foldl(*args, **kwargs)

foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b

Left-associative fold of a structure.

hask.Data.Foldable.foldl_(*args, **kwargs)

foldl_ :: Foldable t => (b -> a -> b) -> b -> t a -> b

Left-associative fold of a structure. but with strict application of the operator.

hask.Data.Foldable.foldl1(*args, **kwargs)

foldl1 :: Foldable t => (a -> a -> a) -> t a -> a

A variant of foldl that has no base case, and thus may only be applied to non-empty structures.

hask.Data.Foldable.toList(*args, **kwargs)

toList :: Foldable t => t a -> [a]

List of elements of a structure, from left to right.

hask.Data.Foldable.length(*args, **kwargs)

length :: Foldable t => t a -> int

Returns the size/length of a finite structure as an int.

hask.Data.Foldable.null(*args, **kwargs)

null :: Foldable t => t a -> Bool

Test whether the structure is empty.

hask.Data.Foldable.elem(*args, **kwargs)

elem :: (Foldable t, Eq a) => a -> t a -> bool

Does the element occur in the structure?

hask.Data.Foldable.maximum(*args, **kwargs)

maximum :: (Foldable t, forall a. Ord a) => t a -> a

The largest element of a non-empty structure.

hask.Data.Foldable.minimum(*args, **kwargs)

minimum :: (Foldable t, forall a. Ord a) => t a -> a

The least element of a non-empty structure.

hask.Data.Foldable.sum(*args, **kwargs)

sum :: (Foldable t, Num a) => t a -> a

The sum function computes the sum of the numbers of a structure.

hask.Data.Foldable.product(*args, **kwargs)

product :: (Foldablet, Num a) => t a -> a

The product function computes the product of the numbers of a structure.

hask.Data.Foldable.foldlM(*args, **kwargs)

foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b

Monadic fold over the elements of a structure, associating to the right, i.e. from right to left.

hask.Data.Foldable.foldrM(*args, **kwargs)

foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b

Monadic fold over the elements of a structure, associating to the left, i.e. from left to right.

hask.Data.Foldable.traverse_(*args, **kwargs)

traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()

Map each element of a structure to an action, evaluate these actions from left to right, and ignore the results. For a version that doesn’t ignore the results see traverse.

hask.Data.Foldable.for_(*args, **kwargs)

for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()

for_ is traverse_ with its arguments flipped. For a version that doesn’t ignore the results see for.

hask.Data.Foldable.sequenceA_(*args, **kwargs)

sequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f ()

Evaluate each action in the structure from left to right, and ignore the results. For a version that doesn’t ignore the results see sequenceA.

hask.Data.Foldable.mapM_(*args, **kwargs)

mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()

Map each element of a structure to a monadic action, evaluate these actions from left to right, and ignore the results. For a version that doesn’t ignore the results see mapM.

As of base 4.8.0.0, mapM_ is just traverse_, specialized to Monad.

hask.Data.Foldable.forM_(*args, **kwargs)

forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()

forM_ is mapM_ with its arguments flipped. For a version that doesn’t ignore the results see forM.

As of base 4.8.0.0, forM_ is just for_, specialized to Monad.

hask.Data.Foldable.sequence_(*args, **kwargs)

sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()

Evaluate each monadic action in the structure from left to right, and ignore the results. For a version that doesn’t ignore the results see sequence.

As of base 4.8.0.0, sequence_ is just sequenceA_, specialized to Monad.

hask.Data.Foldable.concat(*args, **kwargs)

concat :: Foldable t => t [a] -> [a]

The concatenation of all the elements of a container of lists.

hask.Data.Foldable.concatMap(*args, **kwargs)

concatMap :: Foldable t => (a -> [b]) -> t a -> [b]

Map a function over all the elements of a container and concatenate the resulting lists.

hask.Data.Foldable.and_(*args, **kwargs)

and :: Foldable t => t bool -> bool

and returns the conjunction of a container of Bools. For the result to be True, the container must be finite; False, however, results from a False value finitely far from the left end.

hask.Data.Foldable.or_(*args, **kwargs)

or :: Foldable t => t bool -> bool

or returns the disjunction of a container of Bools. For the result to be False, the container must be finite; True, however, results from a True value finitely far from the left end.

hask.Data.Foldable.any_(*args, **kwargs)

any :: Foldable t => (a -> bool) -> t a -> bool

Determines whether any element of the structure satisfies the predicate.

hask.Data.Foldable.all_(*args, **kwargs)

all :: Foldable t => (a -> bool) -> t a -> bool

Determines whether all elements of the structure satisfy the predicate.

hask.Data.Foldable.maximumBy_(*args, **kwargs)

maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a

The largest element of a non-empty structure with respect to the given comparison function.

hask.Data.Foldable.minimumBy_(*args, **kwargs)

minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a

The least element of a non-empty structure with respect to the given comparison function.

hask.Data.Foldable.notElem(*args, **kwargs)

notElem :: (Foldable t, Eq a) => a -> t a -> bool

notElem is the negation of elem.

hask.Data.Foldable.find(*args, **kwargs)

find :: Foldable t => (a -> bool) -> t a -> Maybe a

The find function takes a predicate and a structure and returns the leftmost element of the structure matching the predicate, or Nothing if there is no such element.

hask.Data.Functor – The Data.Functor

class hask.Data.Functor.Functor[source]

The Functor class is used for types that can be mapped over. Instances of Functor should satisfy the following laws:

fmap(id)  ==  id
fmap(f * g)  ==  fmap(f * (fmap g))

Attributes:

  • fmap
  • __rmul__

Minimal complete definition:

  • fmap

hask.Data.List – The Data.List

hask.Data.List.head(*args, **kwargs)

head :: [a] -> a

Extract the first element of a list, which must be non-empty.

hask.Data.List.last(*args, **kwargs)

last :: [a] -> a

Extract the last element of a list, which must be finite and non-empty.

hask.Data.List.tail(*args, **kwargs)

tail :: [a] -> [a]

Extract the elements after the head of a list, which must be non-empty.

hask.Data.List.init(*args, **kwargs)

init :: [a] -> [a]

Return all the elements of a list except the last one. The list must be non-empty.

hask.Data.List.uncons(*args, **kwargs)

uncons :: [a] -> Maybe (a, [a])

Decompose a list into its head and tail. If the list is empty, returns Nothing. If the list is non-empty, returns Just((x, xs)), where x is the head of the list and xs its tail.

hask.Data.List.null(*args, **kwargs)

null :: [a] -> bool

Test whether the structure is empty.

hask.Data.List.length(*args, **kwargs)

length :: [a] -> int

Returns the size/length of a finite structure as an Int. The default implementation is optimized for structures that are similar to cons-lists, because there is no general way to do better.

hask.Data.List.map(*args, **kwargs)

map :: (a -> b) -> [a] -> [b]

map(f, xs) is the list obtained by applying f to each element of xs

hask.Data.List.reverse(*args, **kwargs)

reverse :: [a] -> [a]

reverse(xs) returns the elements of xs in reverse order. xs must be finite.

hask.Data.List.intersperse(*args, **kwargs)

intersperse :: a -> [a] -> [a]

The intersperse function takes an element and a list and intersperses that element between the elements of the list.

hask.Data.List.intercalate(*args, **kwargs)

intercalate :: [a] -> [[a]] -> [a]

intercalate(xs,xss) is equivalent to concat(intersperse(xs,xss)). It inserts the list xs in between the lists in xss and concatenates the result.

hask.Data.List.transpose(*args, **kwargs)

transpose :: [[a]] -> [[a]]

The transpose function transposes the rows and columns of its argument.

hask.Data.List.subsequences(*args, **kwargs)

subsequences :: [a] -> [[a]]

The subsequences function returns the list of all subsequences of the argument.

hask.Data.List.permutations(*args, **kwargs)

permutations :: [a] -> [[a]]

The permutations function returns the list of all permutations of the argument.

hask.Data.List.foldl(*args, **kwargs)

foldl :: (b -> a -> b) -> b -> [a] -> b

foldl, applied to a binary operator, a starting value (typically the left-identity of the operator), and a list, reduces the list using the binary operator, from left to right. The list must be finite.

hask.Data.List.foldl_(*args, **kwargs)

foldl_ :: (b -> a -> b) -> b -> [a] -> b

A strict version of foldl.

hask.Data.List.foldl1(*args, **kwargs)

foldl1 :: (a -> a -> a) -> [a] -> a

foldl1 is a variant of foldl that has no starting value argument, and thus must be applied to non-empty lists.

hask.Data.List.foldl1_(*args, **kwargs)

foldl1_ :: (a -> a -> a) -> [a] -> a

A strict version of foldl1

hask.Data.List.foldr(*args, **kwargs)

foldr :: (a -> b -> b) -> b -> [a] -> b

foldr, applied to a binary operator, a starting value (typically the right-identity of the operator), and a list, reduces the list using the binary operator, from right to left

hask.Data.List.foldr1(*args, **kwargs)

foldr1 :: (a -> a -> a) -> [a] -> a

foldr1 is a variant of foldr that has no starting value argument, and thus must be applied to non-empty lists.

hask.Data.List.concat(*args, **kwargs)

concat :: [[a]] -> [a]

Concatenate a list of lists.

hask.Data.List.concatMap(*args, **kwargs)

concatMap :: (a -> [b]) -> [a] -> [b]

Map a function over a list and concatenate the results.

hask.Data.List.and_(*args, **kwargs)

and_ :: [Bool] -> Bool

and returns the conjunction of a Boolean list. For the result to be True, the list must be finite; False, however, results from a False value at a finite index of a finite or infinite list.

hask.Data.List.or_(*args, **kwargs)

or_ :: [Bool] -> Bool

or returns the disjunction of a Boolean list. For the result to be False, the list must be finite; True, however, results from a True value at a finite index of a finite or infinite list.

hask.Data.List.any(*args, **kwargs)

any :: (a -> Bool) -> [a] -> Bool

Applied to a predicate and a list, any determines if any element of the list satisfies the predicate. For the result to be False, the list must be finite; True, however, results from a True value for the predicate applied to an element at a finite index of a finite or infinite list.

hask.Data.List.all(*args, **kwargs)

all :: (a -> Bool) -> [a] -> Bool

Applied to a predicate and a list, all determines if all elements of the list satisfy the predicate. For the result to be True, the list must be finite; False, however, results from a False value for the predicate applied to an element at a finite index of a finite or infinite list.

hask.Data.List.sum(*args, **kwargs)

sum :: Num a => [a] -> a

The sum function computes the sum of a finite list of numbers.

hask.Data.List.product(*args, **kwargs)

product :: Num a => [a] -> a

The product function computes the product of a finite list of numbers.

hask.Data.List.minimum(*args, **kwargs)

minimum :: Ord a => [a] -> a

minimum returns the minimum value from a list, which must be non-empty, finite, and of an ordered type. It is a special case of minimumBy, which allows the programmer to supply their own comparison function.

hask.Data.List.maximum(*args, **kwargs)

maximum :: Ord a => [a] -> a

maximum returns the maximum value from a list, which must be non-empty, finite, and of an ordered type. It is a special case of maximumBy, which allows the programmer to supply their own comparison function.

hask.Data.List.scanl(*args, **kwargs)

scanl :: (b -> a -> b) -> b -> [a] -> [b]

scanl is similar to foldl, but returns a list of successive reduced values from the left

hask.Data.List.scanl1(*args, **kwargs)

scanl1 :: (a -> a -> a) -> [a] -> [a]

scanl1 is a variant of scanl that has no starting value argument

hask.Data.List.scanr(*args, **kwargs)

scanr :: (a -> b -> b) -> b -> [a] -> [b]

scanr is the right-to-left dual of scanl.

hask.Data.List.scanr1(*args, **kwargs)

scanr1 :: (a -> a -> a) -> [a] -> [a]

scanr1 is a variant of scanr that has no starting value argument.

hask.Data.List.mapAccumL(*args, **kwargs)

mapAccumL :: (a -> x -> (a, y)) -> a -> [x] -> (a, [y])

The mapAccumL function behaves like a combination of map and foldl; it applies a function to each element of a list, passing an accumulating parameter from left to right, and returning a final value of this accumulator together with the new list.

hask.Data.List.mapAccumR(*args, **kwargs)

mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])

The mapAccumR function behaves like a combination of map and foldr; it applies a function to each element of a list, passing an accumulating parameter from right to left, and returning a final value of this accumulator together with the new list.

hask.Data.List.iterate(*args, **kwargs)

iterate :: (a -> a) -> a -> [a]

iterate(f, x) returns an infinite List of repeated applications of f to x: iterate(f, x) == [x, f(x), f(f(x)), …]

hask.Data.List.repeat(*args, **kwargs)

repeat :: a -> [a]

repeat(x) is an infinite list, with x the value of every element.

hask.Data.List.replicate(*args, **kwargs)

replicate :: Int -> a -> [a]

replicate(n, x) is a list of length n with x the value of every element.

hask.Data.List.cycle(*args, **kwargs)

cycle :: [a] -> [a]

cycle ties a finite list into a circular one, or equivalently, the infinite repetition of the original list. It is the identity on infinite lists.

hask.Data.List.unfoldr(*args, **kwargs)

unfoldr :: (b -> Maybe (a, b)) -> b -> [a]

The unfoldr function is a dual to foldr: while foldr reduces a list to a summary value, unfoldr builds a list from a seed value. The function takes the element and returns Nothing if it is done producing the list or returns Just (a,b), in which case, a is prepended to the list and b is used as the next element in a recursive call

hask.Data.List.take(*args, **kwargs)

take :: Int -> [a] -> [a]

take(n), applied to a list xs, returns the prefix of xs of length n, or xs itself if n > length xs

hask.Data.List.drop(*args, **kwargs)

drop :: Int -> [a] -> [a]

drop(n, xs) returns the suffix of xs after the first n elements, or [] if n > length xs

hask.Data.List.splitAt(*args, **kwargs)

splitAt :: Int -> [a] -> ([a], [a])

splitAt(n, xs) returns a tuple where first element is xs prefix of length n and second element is the remainder of the list

hask.Data.List.takeWhile(*args, **kwargs)

takeWhile :: (a -> Bool) -> [a] -> [a]

takeWhile, applied to a predicate p and a list xs, returns the longest prefix (possibly empty) of xs of elements that satisfy p

hask.Data.List.dropWhile(*args, **kwargs)

dropWhile :: (a -> Bool) -> [a] -> [a]

dropWhile(p, xs) returns the suffix remaining after takeWhile(p, xs)

hask.Data.List.dropWhileEnd(*args, **kwargs)

dropWhileEnd :: (a -> Bool) -> [a] -> [a]

The dropWhileEnd function drops the largest suffix of a list in which the given predicate holds for all elements.

hask.Data.List.span(*args, **kwargs)

span :: (a -> Bool) -> [a] -> ([a], [a])

span, applied to a predicate p and a list xs, returns a tuple where first element is longest prefix (possibly empty) of xs of elements that satisfy p and second element is the remainder of the list

hask.Data.List.break_(*args, **kwargs)

break :: (a -> Bool) -> [a] -> ([a], [a])

break, applied to a predicate p and a list xs, returns a tuple where first element is longest prefix (possibly empty) of xs of elements that do not satisfy p and second element is the remainder of the list

hask.Data.List.stripPrefix(*args, **kwargs)

stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]

The stripPrefix function drops the given prefix from a list. It returns Nothing if the list did not start with the prefix given, or Just the list after the prefix, if it does.

hask.Data.List.group(*args, **kwargs)

group :: Eq a => [a] -> [[a]]

The group function takes a list and returns a list of lists such that the concatenation of the result is equal to the argument. Moreover, each sublist in the result contains only equal elements. It is a special case of groupBy, which allows the programmer to supply their own equality test.

hask.Data.List.inits(*args, **kwargs)

inits :: [a] -> [[a]]

The inits function returns all initial segments of the argument, shortest first.

hask.Data.List.tails(*args, **kwargs)

tails :: [a] -> [[a]]

The tails function returns all final segments of the argument, longest first.

hask.Data.List.isPrefixOf(*args, **kwargs)

isPrefixOf :: Eq a => [a] -> [a] -> Bool

The isPrefixOf function takes two lists and returns True iff the first list is a prefix of the second.

hask.Data.List.isSuffixOf(*args, **kwargs)

isSuffixOf :: Eq a => [a] -> [a] -> Bool

The isSuffixOf function takes two lists and returns True iff the first list is a suffix of the second. The second list must be finite.

hask.Data.List.isInfixOf(*args, **kwargs)

isInfixOf :: Eq a => [a] -> [a] -> Bool

The isInfixOf function takes two lists and returns True iff the first list is contained, wholly and intact, anywhere within the second.

hask.Data.List.isSubsequenceOf(*args, **kwargs)

isSubsequenceOf :: Eq a => [a] -> [a] -> Bool

The isSubsequenceOf function takes two lists and returns True if the first list is a subsequence of the second list.

isSubsequenceOf(x, y) is equivalent to elem(x, subsequences(y))

hask.Data.List.elem(*args, **kwargs)

elem :: Eq a => a -> [a] -> Bool

elem is the list membership predicate, elem(x, xs). For the result to be False, the list must be finite; True, however, results from an element equal to x found at a finite index of a finite or infinite list.

hask.Data.List.notElem(*args, **kwargs)

notElem :: Eq a => a -> [a] -> Bool

notElem is the negation of elem().

hask.Data.List.lookup(*args, **kwargs)

lookup :: Eq a => a -> [(a, b)] -> Maybe b

lookup(key, assocs) looks up a key in an association list.

hask.Data.List.find(*args, **kwargs)

find :: (a -> Bool) -> [a] -> Maybe a

The find function takes a predicate and a structure and returns the leftmost element of the structure matching the predicate, or Nothing if there is no such element.

hask.Data.List.filter(*args, **kwargs)

filter :: (a -> Bool) -> [a] -> [a]

filter, applied to a predicate and a list, returns the list of those elements that satisfy the predicate

hask.Data.List.partition(*args, **kwargs)

partition :: (a -> Bool) -> [a] -> ([a], [a])

The partition function takes a predicate a list and returns the pair of lists of elements which do and do not satisfy the predicate.

hask.Data.List.elemIndex(*args, **kwargs)

elemIndex :: Eq a => a -> [a] -> Maybe Int

The elemIndex function returns the index of the first element in the given list which is equal (by ==) to the query element, or Nothing if there is no such element.

hask.Data.List.elemIndices(*args, **kwargs)

elemIndices :: Eq a => a -> [a] -> [Int]

The elemIndices function extends elemIndex, by returning the indices of all elements equal to the query element, in ascending order.

hask.Data.List.findIndex(*args, **kwargs)

findIndex :: (a -> Bool) -> [a] -> Maybe Int

The findIndex function takes a predicate and a list and returns the index of the first element in the list satisfying the predicate, or Nothing if there is no such element.

hask.Data.List.findIndicies(*args, **kwargs)

findIndices :: (a -> Bool) -> [a] -> [Int]

The findIndices function extends findIndex, by returning the indices of all elements satisfying the predicate, in ascending order.

hask.Data.List.zip(*args, **kwargs)

zip :: [a] -> [b] -> [(a, b)]

zip takes two lists and returns a list of corresponding pairs. If one input list is short, excess elements of the longer list are discarded.

hask.Data.List.zip3(*args, **kwargs)

zip3 :: [a] -> [b] -> [c] -> [(a, b, c)]

zip3 takes three lists and returns a list of triples, analogous to zip.

hask.Data.List.zip4(*args, **kwargs)

zip4 :: [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)]

The zip4 function takes four lists and returns a list of quadruples, analogous to zip.

hask.Data.List.zip5(*args, **kwargs)

zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)]

The zip5 function takes five lists and returns a list of five-tuples, analogous to zip.

hask.Data.List.zip6(*args, **kwargs)

zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)]

The zip6 function takes six lists and returns a list of six-tuples, analogous to zip.

hask.Data.List.zip7(*args, **kwargs)

zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a, b, c, d, e, f, g)]

The zip7 function takes seven lists and returns a list of seven-tuples, analogous to zip.

hask.Data.List.zipWith(*args, **kwargs)

zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]

zipWith generalises zip by zipping with the function given as the first argument, instead of a tupling function. For example, zipWith (+) is applied to two lists to produce the list of corresponding sums.

hask.Data.List.zipWith3(*args, **kwargs)

zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]

The zipWith3 function takes a function which combines three elements, as well as three lists and returns a list of their point-wise combination, analogous to zipWith.

hask.Data.List.zipWith4(*args, **kwargs)

zipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]

The zipWith4 function takes a function which combines four elements, as well as four lists and returns a list of their point-wise combination, analogous to zipWith.

hask.Data.List.zipWith5(*args, **kwargs)

zipWith5 :: (a -> b -> c -> d -> e -> f) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f]

The zipWith5 function takes a function which combines five elements, as well as five lists and returns a list of their point-wise combination, analogous to zipWith.

hask.Data.List.zipWith6(*args, **kwargs)

zipWith6 :: (a -> b -> c -> d -> e -> f -> g) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g]

The zipWith6 function takes a function which combines six elements, as well as six lists and returns a list of their point-wise combination, analogous to zipWith.

hask.Data.List.zipWith7(*args, **kwargs)

zipWith7 :: (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h]

The zipWith7 function takes a function which combines seven elements, as well as seven lists and returns a list of their point-wise combination, analogous to zipWith.

hask.Data.List.unzip(*args, **kwargs)

unzip :: [(a, b)] -> ([a], [b])

unzip transforms a list of pairs into a list of first components and a list of second components.

hask.Data.List.unzip3(*args, **kwargs)

unzip3 :: [(a, b, c)] -> ([a], [b], [c])

The unzip3 function takes a list of triples and returns three lists, analogous to unzip.

hask.Data.List.unzip4(*args, **kwargs)

unzip4 :: [(a, b, c, d)] -> ([a], [b], [c], [d])

The unzip4 function takes a list of quadruples and returns four lists, analogous to unzip.

hask.Data.List.unzip5(*args, **kwargs)

unzip5 :: [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e])

The unzip5 function takes a list of five-tuples and returns five lists, analogous to unzip.

hask.Data.List.unzip6(*args, **kwargs)

unzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f])

The unzip6 function takes a list of six-tuples and returns six lists, analogous to unzip.

hask.Data.List.unzip7(*args, **kwargs)

unzip7 :: [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g])

The unzip7 function takes a list of seven-tuples and returns seven lists, analogous to unzip.

hask.Data.List.nub(*args, **kwargs)

nub :: Eq a => [a] -> [a]

The nub function removes duplicate elements from a list. In particular, it keeps only the first occurrence of each element. (The name nub means essence.) It is a special case of nubBy, which allows the programmer to supply their own equality test.

hask.Data.List.delete(*args, **kwargs)

delete :: Eq a => a -> [a] -> [a]

delete(x) removes the first occurrence of x from its list argument.

It is a special case of deleteBy, which allows the programmer to supply their own equality test.

hask.Data.List.diff(*args, **kwargs)

diff :: :: Eq a => [a] -> [a] -> [a]

List difference.

hask.Data.List.union(*args, **kwargs)

union :: Eq a => [a] -> [a] -> [a]

The union function returns the list union of the two lists.

Duplicates, and elements of the first list, are removed from the the second list, but if the first list contains duplicates, so will the result. It is a special case of unionBy, which allows the programmer to supply their own equality test.

hask.Data.List.intersect(*args, **kwargs)

intersect :: Eq a => [a] -> [a] -> [a]

The intersect function takes the list intersection of two lists. It is a special case of intersectBy, which allows the programmer to supply their own equality test. If the element is found in both the first and the second list, the element from the first list will be used.

hask.Data.List.sort(*args, **kwargs)

sort :: Ord a => [a] -> [a]

The sort function implements a stable sorting algorithm. It is a special case of sortBy, which allows the programmer to supply their own comparison function.

Note: Current implementation is not lazy

hask.Data.List.sortOn(*args, **kwargs)

sortOn :: Ord b => (a -> b) -> [a] -> [a]

Sort a list by comparing the results of a key function applied to each element.

Note: Current implementation is not lazy

hask.Data.List.insert(*args, **kwargs)

insert :: Ord a => a -> [a] -> [a]

The insert function takes an element and a list and inserts the element into the list at the first position where it is less than or equal to the next element. In particular, if the list is sorted before the call, the result will also be sorted.

hask.Data.List.nubBy(*args, **kwargs)

nubBy :: (a -> a -> Bool) -> [a] -> [a]

The nubBy function behaves just like nub, except it uses a user-supplied equality predicate instead of the overloaded == function.

hask.Data.List.deleteBy(*args, **kwargs)

deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]

The deleteBy function behaves like delete, but takes a user-supplied equality predicate.

hask.Data.List.deleteFirstBy(*args, **kwargs)

deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]

The deleteFirstsBy function takes a predicate and two lists and returns the first list with the first occurrence of each element of the second list removed.

hask.Data.List.unionBy(*args, **kwargs)

unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]

The unionBy function is the non-overloaded version of union.

hask.Data.List.intersectBy(*args, **kwargs)

intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]

The intersectBy function is the non-overloaded version of intersect.

hask.Data.List.groupBy(*args, **kwargs)

groupBy :: (a -> a -> Bool) -> [a] -> [[a]]

The groupBy function is the non-overloaded version of group.

hask.Data.List.sortBy(*args, **kwargs)

sortBy :: (a -> a -> Ordering) -> [a] -> [a]

The sortBy function is the non-overloaded version of sort.

hask.Data.List.insertBy(*args, **kwargs)

insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]

The non-overloaded version of insert.

hask.Data.List.maximumBy(*args, **kwargs)

maximumBy :: (a -> a -> Ordering) -> [a] -> a

The maximumBy function takes a comparison function and a list and returns the greatest element of the list by the comparison function. The list must be finite and non-empty.

hask.Data.List.minimumBy(*args, **kwargs)

minimumBy :: (a -> a -> Ordering) -> [a] -> a

The minimumBy function takes a comparison function and a list and returns the least element of the list by the comparison function. The list must be finite and non-empty.

hask.Data.List.genericLength(*args, **kwargs)

genericLength :: Num i => [a] -> i

The genericLength function is an overloaded version of length. In particular, instead of returning an Int, it returns any type which is an instance of Num. It is, however, less efficient than length.

hask.Data.List.genericTake(*args, **kwargs)

genericTake :: Integral i => i -> [a] -> [a]

The genericTake function is an overloaded version of take, which accepts any Integral value as the number of elements to take.

hask.Data.List.genericDrop(*args, **kwargs)

genericDrop :: Integral i => i -> [a] -> [a]

The genericDrop function is an overloaded version of drop, which accepts any Integral value as the number of elements to drop.

hask.Data.List.genericSplitAt(*args, **kwargs)

genericSplitAt :: Integral i => i -> [a] -> ([a], [a])

The genericSplitAt function is an overloaded version of splitAt, which accepts any Integral value as the position at which to split.

hask.Data.List.genericIndex(*args, **kwargs)

genericIndex :: Integral i => [a] -> i -> a

The genericIndex function is an overloaded version of !!, which accepts any Integral value as the index.

hask.Data.List.genericReplicate(*args, **kwargs)

genericReplicate :: Integral i => i -> a -> [a]

The genericReplicate function is an overloaded version of replicate, which accepts any Integral value as the number of repetitions to make.

hask.Data.Maybe – The Data.Maybe

hask.Data.Maybe.Maybe

The ADT Maybe:

data.Maybe("a") == d.Nothing | d.Just("a") & deriving(Read, Show, Eq, Ord)
hask.Data.Maybe.Nothing
hask.Data.Maybe.Just(a)
hask.Data.Maybe.in_maybe(fn)[source]

Decorator for monadic error handling.

If the decorated function raises an exception, return Nothing. Otherwise, take the result and wrap it in a Just.

hask.Data.Maybe.maybe(*args, **kwargs)

maybe :: b -> (a -> b) -> Maybe a -> b

The maybe function takes a default value, a function, and a Maybe value. If the Maybe value is Nothing, the function returns the default value. Otherwise, it applies the function to the value inside the Just and returns the result.

hask.Data.Maybe.isJust(*args, **kwargs)

isJust :: [Maybe a] -> bool

hask.Data.Maybe.isNothing(*args, **kwargs)

isNothing :: [Maybe a] -> bool

hask.Data.Maybe.fromJust(*args, **kwargs)

fromJust :: [Maybe a] -> a

hask.Data.Maybe.listToMaybe(*args, **kwargs)

listToMaybe :: [a] -> [Maybe a]

hask.Data.Maybe.maybeToList(*args, **kwargs)

maybeToList :: Maybe a -> [a]

The maybeToList function returns an empty list when given Nothing or a singleton list when not given Nothing.

hask.Data.Maybe.catMaybes(*args, **kwargs)

catMaybes :: [Maybe a] -> [a]

The catMaybes function takes a list of Maybes and returns a list of all the Just values.

hask.Data.Maybe.mapMaybe(*args, **kwargs)

mapMaybe :: (a -> Maybe b) -> [a] -> [b]

The mapMaybe function is a version of map which can throw out elements. In particular, the functional argument returns something of type Maybe b. If this is Nothing, no element is added on to the result list. If it is Just b, then b is included in the result list.

hask.Data.Monoid – The Data.Monoid

class hask.Data.Monoid.Monoid[source]

The class of monoids (types with an associative binary operation that has an identity)

Attributes:

  • mempty
  • mappend
  • mconcat

Minimal complete definition:

  • mempty
  • mappend
  • mconcat
hask.Data.Monoid.mappend(*args, **kwargs)

mappend :: a -> a -> a

An associative operation

hask.Data.Monoid.mconcat(*args, **kwargs)

mconcat :: [a] -> a

Fold a list using the monoid.

hask.Data.Num – The Data.Num

class hask.Data.Num.Num[source]

Basic numeric class.

Dependencies:

Attributes:

  • __add__
  • __mul__
  • __abs__
  • signum
  • fromInteger
  • __neg__
  • __sub__

Minimal complete definition:

  • add
  • mul
  • abs
  • signum
  • fromInteger
  • negate
class hask.Data.Num.Fractional[source]

Fractional numbers, supporting real division.

Dependencies:

Attributes:

  • fromRational
  • recip
  • __div__

Minimal complete definition:

  • fromRational
  • div
class hask.Data.Num.Floating[source]

Trigonometric and hyperbolic functions and related functions.

Dependencies:

Attributes:

  • pi
  • exp
  • sqrt
  • log
  • pow
  • logBase
  • sin
  • tan
  • cos
  • asin
  • atan
  • acos
  • sinh
  • tanh
  • cosh
  • asinh
  • atanh
  • acosh

Minimal complete definition:

  • pi
  • exp
  • sqrt
  • log
  • pow
  • logBase
  • sin
  • tan
  • cos
  • asin
  • atan
  • acos
  • sinh
  • tanh
  • cosh
  • asinh
  • atanh
  • acosh
class hask.Data.Num.Real[source]

Real numbers.

Dependencies:

Attributes:

  • toRational

Minimal complete definition:

  • toRational
class hask.Data.Num.Integral[source]

Integral numbers, supporting integer division.

Dependencies:

Attributes:

  • quotRem
  • toInteger
  • quot
  • rem
  • div
  • mod

Minimal complete definition:

  • quotRem
  • toInteger
  • quot
  • rem
  • div
  • mod
class hask.Data.Num.RealFrac[source]

Extracting components of fractions.

Dependencies:

Attributes:

  • properFraction
  • truncate
  • round
  • ceiling
  • floor

Minimal complete definition:

  • properFraction
  • truncate
  • round
  • ceiling
  • floor
class hask.Data.Num.RealFloat[source]

Efficient, machine-independent access to the components of a floating-point number.

Dependencies:

Attributes:

  • floatRange
  • isNan
  • isInfinite
  • isNegativeZero
  • atan2

Minimal complete definition:

  • floatRange
  • isNan
  • isInfinite
  • isNegativeZero
  • atan2
Ratio

The ADT Ratio:

Ratio, R =\
   data.Ratio("a") == d.R("a", "a") & deriving(Eq)
Rational

A Ratio over int. Defined as t(Ratio, int).

hask.Data.Num.R(a, a)

The constructor of a Ratio.

hask.Data.Num.negate(*args, **kwargs)

signum :: Num a => a -> a

Unary negation.

hask.Data.Num.signum(*args, **kwargs)

signum :: Num a => a -> a

Sign of a number. The functions abs and signum should satisfy the law: abs x * signum x == x For real numbers, the signum is either -1 (negative), 0 (zero) or 1 (positive).

hask.Data.Num.abs(*args, **kwargs)

abs :: Num a => a -> a

Absolute value.

hask.Data.Num.recip(*args, **kwargs)

recip :: Fractional a => a -> a

Reciprocal fraction.

hask.Data.Num.exp(*args, **kwargs)

exp :: Floating a => a -> a

hask.Data.Num.sqrt(*args, **kwargs)

sqrt :: Floating a => a -> a

hask.Data.Num.log(*args, **kwargs)

log:: Floating a => a -> a

hask.Data.Num.pow(*args, **kwargs)

pow :: Floating a => a -> a -> a

hask.Data.Num.logBase(*args, **kwargs)

logBase :: Floating a => a -> a -> a

hask.Data.Num.sin(*args, **kwargs)

sin :: Floating a => a -> a

hask.Data.Num.cos(*args, **kwargs)

cos :: Floating a => a -> a

hask.Data.Num.tan(*args, **kwargs)

tan :: Floating a => a -> a

hask.Data.Num.asin(*args, **kwargs)

asin :: Floating a => a -> a

hask.Data.Num.atan(*args, **kwargs)

atan :: Floating a => a -> a

hask.Data.Num.acos(*args, **kwargs)

acos :: Floating a => a -> a

hask.Data.Num.sinh(*args, **kwargs)

sinh :: Floating a => a -> a

hask.Data.Num.tanh(*args, **kwargs)

tanh :: Floating a => a -> a

hask.Data.Num.cosh(*args, **kwargs)

cosh :: Floating a => a -> a

hask.Data.Num.asinh(*args, **kwargs)

asinh :: Floating a => a -> a

hask.Data.Num.atanh(*args, **kwargs)

atanh :: Floating a => a -> a

hask.Data.Num.acosh(*args, **kwargs)

acosh :: Floating a => a -> a

hask.Data.Num.toRational(*args, **kwargs)

toRational :: Real a => a -> Rational

Conversion to Rational.

hask.Data.Num.toRatio(*args, **kwargs)

toRatio :: Integral a => a -> a -> Ratio a

Conversion to Ratio.

hask.Data.Num.properFraction(*args, **kwargs)

properFraction :: RealFrac a, Integral b => a -> (b, a)

The function properFraction takes a real fractional number x and returns a pair (n,f) such that x = n+f, and:

n is an integral number with the same sign as x; and f is a fraction with the same type and sign as x, and with absolute value less than 1.
hask.Data.Num.truncate(*args, **kwargs)

truncate :: RealFrac a, Integral b => a -> b

truncate(x) returns the integer nearest x between zero and x

hask.Data.Num.round(*args, **kwargs)

round :: RealFrac a, Integral b => a -> b

round(x) returns the nearest integer to x; the even integer if x is equidistant between two integers

hask.Data.Num.ceiling(*args, **kwargs)

ceiling :: RealFrac a, Integral b => a -> b

ceiling(x) returns the least integer not less than x

hask.Data.Num.floor(*args, **kwargs)

floor :: RealFrac a, Integral b => a -> b

floor(x) returns the greatest integer not greater than x

hask.Data.Num.isNaN(*args, **kwargs)

isNaN :: RealFloat a => a -> bool

True if the argument is an IEEE “not-a-number” (NaN) value

hask.Data.Num.isInfinite(*args, **kwargs)

isInfinite :: RealFloat a => a -> bool

True if the argument is an IEEE infinity or negative infinity

hask.Data.Num.isNegativeZero(*args, **kwargs)

isNegativeZero :: RealFloat a => a -> bool

True if the argument is an IEEE negative zero

hask.Data.Num.atan2(*args, **kwargs)

atan2 :: RealFloat a => a -> a -> a

a version of arctangent taking two real floating-point arguments

hask.Data.Ord – The Data.Ord

Ordering

The ADT Ordering:

data Ordering = LT | EQ | GT deriving(Show, Eq, Ord, Bounded)
LT
EQ
GT
hask.Data.Ord.max(*args, **kwargs)

max :: a -> a -> a

Maximum function.

hask.Data.Ord.min(*args, **kwargs)

min :: a -> a -> a

Minumum function.

hask.Data.Ord.compare(*args, **kwargs)

compare :: a -> a -> Ordering

Comparison function.

hask.Data.Ord.comparing(*args, **kwargs)

comparing :: Ord a => (b -> a) -> b -> b -> Ordering

comparing(p, x, y) = compare(p(x), p(y))

Useful combinator for use in conjunction with the xxxBy family of functions from Data.List, for example:

... sortBy (comparing(fst)) ...

hask.Data.Ratio – The Data.Ratio

hask.Data.Ratio.numerator(*args, **kwargs)

numerator :: Integral a => Ratio a -> a

Extract the numerator of the ratio in reduced form: the numerator and denominator have no common factor and the denominator is positive.

hask.Data.Ratio.denominator(*args, **kwargs)

denominator :: Integral a => Ratio a -> a

Extract the denominator of the ratio in reduced form: the numerator and denominator have no common factor and the denominator is positive.

hask.Data.Ratio.approxRational(*args, **kwargs)

approxRational :: RealFrac a => a -> a -> Rational

approxRational, applied to two real fractional numbers x and epsilon, returns the simplest rational number within epsilon of x. A rational number y is said to be simpler than another y’ if abs(numerator(y)) <= abs(numerator(y_)) and denominator(y) <= denominator(y_).

Any real interval contains a unique simplest rational; in particular, note that 0/1 is the simplest rational of all.

hask.Data.String – The Data.String

hask.Data.String.lines(*args, **kwargs)

lines :: String -> [String]

lines breaks a string up into a list of strings at newline characters. The resulting strings do not contain newlines.

hask.Data.String.words(*args, **kwargs)

words :: String -> [String]

words breaks a string up into a list of words, which were delimited by white space.

hask.Data.String.unlines(*args, **kwargs)

lines :: [String] -> String

unlines is an inverse operation to lines. It joins lines, after appending a terminating newline to each.

hask.Data.String.unwords(*args, **kwargs)

unwords :: [String] -> String

unwords is an inverse operation to words. It joins words with separating spaces.

hask.Data.Traversable – The Data.Traversable

class hask.Data.Traversable.Traversable[source]

Functors representing data structures that can be traversed from left to right.

Dependencies:

Attributes:

  • traverse
  • sequenceA
  • mapM
  • sequence

Minimal complete definition:

  • traverse
hask.Data.Traversable.traverse(*args, **kwargs)

traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b)

Map each element of a structure to an action, evaluate these these actions from left to right, and collect the results. actions from left to right, and collect the results. For a version that ignores the results see traverse_.

hask.Data.Traversable.sequenceA(*args, **kwargs)

sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a)

Evaluate each action in the structure from left to right, and and collect the results. For a version that ignores the results see sequenceA_.

hask.Data.Traversable.mapM(*args, **kwargs)

mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b)

Map each element of a structure to a monadic action, evaluate these actions from left to right, and collect the results. For a version that ignores the results see mapM_.

hask.Data.Traversable.sequence(*args, **kwargs)

sequence :: (Traversable t, Monad m) => t (m a) -> m (t a)

Evaluate each monadic action in the structure from left to right, and collect the results. For a version that ignores the results see sequence_.

hask.Data.Traversable.for1(*args, **kwargs)

for1 :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b)

for1 is traverse with its arguments flipped. For a version that ignores the results see for1_.

hask.Data.Traversable.forM(*args, **kwargs)

forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)

forM is mapM with its arguments flipped. For a version that ignores the results see forM_.

hask.Data.Traversable.mapAccumL(*args, **kwargs)

mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)

The mapAccumL function behaves like a combination of fmap and foldl; it applies a function to each element of a structure, passing an accumulating parameter from left to right, and returning a final value of this accumulator together with the new structure.

hask.Data.Traversable.mapAccumR(*args, **kwargs)

mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)

The mapAccumR function behaves like a combination of fmap and foldr; it applies a function to each element of a structure, passing an accumulating parameter from right to left, and returning a final value of this accumulator together with the new structure.

hask.Data.Tuple – The Data.Tuple

hask.Data.Tuple.fst(*args, **kwargs)

fst :: (a, b) -> a

Extract the first component of a pair.

hask.Data.Tuple.snd(*args, **kwargs)

snd :: (a, b) -> b

Extract the second component of a pair.

hask.Data.Tuple.curry(*args, **kwargs)

curry :: ((a, b) -> c) -> a -> b -> c

curry converts an uncurried function to a curried function.

hask.Data.Tuple.uncurry(*args, **kwargs)

uncurry :: (a -> b -> c) -> (a, b) -> c

uncurry converts a curried function to a function on pairs.

hask.Data.Tuple.swap(*args, **kwargs)

swap :: (a, b) -> (b, a)

Swap the components of a pair.

hask.Python.builtins – Python builtins as Hask functions

Typed wrappers for builtin Python functions.

This makes it easier to chain lots of things together in function composition without having to manually add type signatures to Python builtins.

Each function is a TypedFunc replacement of the corresponding Python builtin with the right signature.

hask.Python.builtins.callable()

callable ** (H/ "a" >> bool)

hask.Python.builtins.cmp()

cmp ** (H/ "a" >> "a" >> int)

Note

In Python 3, cmp is not a builtin.

hask.Python.builtins.delattr()

delattr ** (H/ "a" >> str >> None)

hask.Python.builtins.divmod()

divmod ** (H/ "a" >> "b" >> ("c", "c"))

hask.Python.builtins.getattr()

getattr ** (H/ "a" >> str >> "b")

hask.Python.builtins.hasattr()

hasattr ** (H/ "a" >> str >> bool)

hask.Python.builtins.hash()

hash ** (H/ "a" >> int)

hask.Python.builtins.hex()

hex ** (H/ int >> str)

hask.Python.builtins.isinstance()

isinstance ** (H/ "a" >> "b" >> bool)

hask.Python.builtins.issubclass()

issubclass ** (H/ "a" >> "b" >> bool)

hask.Python.builtins.len()

len ** (H/ "a" >> int)

hask.Python.builtins.oct()

oct ** (H/ int >> str)

hask.Python.builtins.repr()

repr ** (H/ "a" >> str)

hask.Python.builtins.setattr()

setattr ** (H/ "a" >> str >> "b" >> None)

hask.Python.builtins.sorted()

sorted ** (H/ "a" >> list)

Changelog

Beta series: 0.x

2018-07-18. Release 0.1.1

  • Repackaging. No functional changes.

2018-07-17. Release 0.1.0

  • Initial release as programmed by the original authors with only the changes to make tests pass in Python 3.

    At this point the examples in the Overview are expected to work well in Python 2.7 and Python 3.4+.

Indices and tables