https://wiki.haskell.org/api.php?action=feedcontributions&user=Benmachine&feedformat=atomHaskellWiki - User contributions [en]2015-04-19T21:59:47ZUser contributionsMediaWiki 1.19.14+dfsg-1https://wiki.haskell.org/PolymorphismPolymorphism2015-01-21T00:50:09Z<p>Benmachine: </p>
<hr />
<div>[[Category:Glossary]]<br />
A value is polymorphic if there is more than one type it can have. Polymorphism is widespread in Haskell and is a key feature of its type system.<br />
<br />
Most polymorphism in Haskell falls into one of two broad categories: [[#Parametric polymorphism|''parametric'']] polymorphism and [[#Ad-hoc polymorphism|''ad-hoc'']] polymorphism.<br />
<br />
=== Parametric polymorphism ===<br />
<br />
Parametric polymorphism refers to when the type of a value contains one or more (unconstrained) ''type variables'', so that the value may adopt any type that results from substituting those variables with concrete types.<br />
<br />
In Haskell, this means any type in which a type variable, denoted by a name in a type beginning with a lowercase letter, appears without constraints (i.e. does not appear to the left of a <tt>=></tt>). In Java and some similar languages, generics (roughly speaking) fill this role.<br />
<br />
For example, the function <hask>id :: a -> a</hask> contains an unconstrained type variable <hask>a</hask> in its type, and so can be used in a context requiring <hask>Char -> Char</hask> or <hask>Integer -> Integer</hask> or <hask>(Bool -> Maybe Bool) -> (Bool -> Maybe Bool)</hask> or any of a literally infinite list of other possibilities. Likewise, the empty list <hask>[] :: [a]</hask> belongs to every list type, and the polymorphic function <hask>map :: (a -> b) -> [a] -> [b]</hask> may operate on any function type. Note, however, that if a single type variable appears multiple times, it must take the same type everywhere it appears, so e.g. the result type of <hask>id</hask> must be the same as the argument type, and the input and output types of the function given to <hask>map</hask> must match up with the list types.<br />
<br />
Since a parametrically polymorphic value does not "know" anything about the unconstrained type variables, it must behave the same regardless of its type. This is a somewhat limiting but extremely useful property known as [[parametricity]].<br />
<br />
=== Ad-hoc polymorphism ===<br />
<br />
Ad-hoc polymorphism refers to when a value is able to adopt any one of several types because it, or a value it uses, has been given a separate definition for each of those types. For example, the <tt>+</tt> operator essentially does something entirely different when applied to floating-point values as compared to when applied to integers – in Python it can even be applied to strings as well. Most languages support at least some ad-hoc polymorphism, but in languages like C it is restricted to only built-in functions and types. Other languages like C++ allow programmers to provide their own overloading, supplying multiple definitions of a single function, to be disambiguated by the types of the arguments. In Haskell, this is achieved via the system of [[type class]]es and class instances.<br />
<br />
Despite the similarity of the name, Haskell's type classes are quite different from the classes of most object-oriented languages. They have more in common with interfaces, in that they specify a series of methods or values by their type signature, to be implemented by an instance declaration.<br />
<br />
So, for example, if my type can be compared for equality (most types can, but some, particularly function types, cannot) then I can give an instance declaration of the <hask>Eq</hask> class. All I have to do is specify the behaviour of the <hask>==</hask> operator on my type, and I gain the ability to use all sorts of functions defined using that operator, e.g. checking if a value of my type is present in a list, or looking up a corresponding value in a list of pairs.<br />
<br />
Unlike the overloading in some languages, overloading in Haskell is not limited to functions – <tt>minBound</tt> is an example of an overloaded ''value'', so that when used as a <tt>Char</tt> it will have value <tt>'\NUL'</tt> while as an <tt>Int</tt> it might be <tt>-2147483648</tt>.<br />
<br />
Haskell even allows class instances to be defined for types which are themselves polymorphic (either ad-hoc or parametrically). So for example, an instance can be defined of <tt>Eq</tt> that says "if <tt>a</tt> has an equality operation, then <tt>[a]</tt> has one". Then, of course, <tt><nowiki>[[a]]</nowiki></tt> will automatically also have an instance, and so complex compound types can have instances built for them out of the instances of their components.<br />
<br />
You can recognise the presence of ad-hoc polymorphism by looking for ''constrained'' type variables: that is, variables that appear to the left of <hask>=></hask>, like in <hask>elem :: (Eq a) => a -> [a] -> Bool</hask>. Note that <hask>lookup :: (Eq a) => a -> [(a,b)] -> Maybe b</hask> exhibits both parametric (in <hask>b</hask>) and ad-hoc (in <hask>a</hask>) polymorphism.<br />
<br />
=== Other kinds of polymorphism ===<br />
<br />
There are several more exotic flavours of polymorphism that are implemented in some extensions to Haskell, e.g. [[rank-N types]] and [[impredicative types]].<br />
<br />
There are some kinds of polymorphism that Haskell doesn't support, or at least not natively, e.g. inclusion polymorphism and subtyping, common in OO languages, where values of one type can act as values of another type.<br />
<br />
== Further reading ==<br />
*[http://lucacardelli.name/Papers/OnUnderstanding.A4.pdf On Understanding Types, Data Abstraction, and Polymorphism (1985)], by Luca Cardelli, Peter Wegner in ACM Computing Surveys.<br />
<br />
*[http://www.cs.utexas.edu/~wcook/Drafts/2009/essay.pdf On Understanding Data Abstraction, Revisited (2009)], by William R. Cook in OOPSLA 2009.<br />
<br />
*[http://en.wikipedia.org/wiki/Type_polymorphism Type polymorphism] at Wikipedia</div>Benmachinehttps://wiki.haskell.org/SeqSeq2014-10-19T15:25:09Z<p>Benmachine: </p>
<hr />
<div><span>{{DISPLAYTITLE:seq}}</span><br />
<br />
The <tt>seq</tt> function is the most basic method of introducing strictness to a Haskell program. <tt>seq :: a -> b -> b</tt> takes two arguments of any type, and returns the second. However, it also has the important property that it is magically strict in its first argument. In essence, <tt>seq</tt> is defined by the following two equations:<br />
<br />
<haskell><br />
⊥ `seq` b = ⊥<br />
a `seq` b = b<br />
</haskell><br />
<br />
See [[Bottom]] for an explanation of the ⊥ symbol.<br />
<br />
A common misconception regarding <tt>seq</tt> is that <tt>seq x</tt> "evaluates" <tt>x</tt>. Well, sort of. <tt>seq</tt> doesn't evaluate anything just by virtue of existing in the source file, all it does is introduce an artificial data dependency of one value on another: when the result of <tt>seq</tt> is evaluated, the first argument must also (sort of; see below) be evaluated. As an example, suppose <tt>x :: Integer</tt>, then <tt>seq x b</tt> behaves essentially like <tt>if x == 0 then b else b</tt> – unconditionally equal to <tt>b</tt>, but forcing <tt>x</tt> along the way. In particular, the expression <tt>x `seq` x</tt> is completely redundant, and always has exactly the same effect as just writing <tt>x</tt>.<br />
<br />
Strictly speaking, the two equations of <tt>seq</tt> are all it must satisfy, and if the compiler can statically prove that the first argument is not ⊥, or that its second argument ''is'', it doesn't have to evaluate anything to meet its obligations. In practice, this almost never happens, and would probably be considered highly counterintuitive behaviour on the part of GHC (or whatever else you use to run your code). However, it ''is'' the case that evaluating <tt>b</tt> and ''then'' <tt>a</tt>, then returning <tt>b</tt> is a perfectly legitimate thing to do; it was to prevent this ambiguity that <tt>pseq</tt> was invented, but that's another story.<br />
<br />
=== Common uses of <tt>seq</tt> ===<br />
<br />
<tt>seq</tt> is typically used in the semantic interpretation of other strictness techniques, like strictness annotations in data types, or GHC's <tt>BangPatterns</tt> extension. For example, the meaning of this:<br />
<br />
<haskell><br />
f !x !y = z<br />
</haskell><br />
<br />
is this:<br />
<br />
<haskell><br />
f x y | x `seq` y `seq` False = undefined<br />
| otherwise = z<br />
</haskell><br />
<br />
although that literal translation may not actually take place.<br />
<br />
<tt>seq</tt> is frequently used with accumulating parameters to ensure that they don't become huge thunks, which will be forced at the end anyway. For example, strict foldl:<br />
<br />
<haskell><br />
foldl' :: (a -> b -> a) -> a -> [b] -> a<br />
foldl' _ z [] = z<br />
foldl' f z (x:xs) = let z' = f z x in z' `seq` foldl' f z' xs<br />
</haskell><br />
<br />
It's also used to define strict application:<br />
<br />
<haskell><br />
($!) :: (a -> b) -> a -> b<br />
f $! x = x `seq` f x<br />
</haskell><br />
<br />
which is useful for some of the same reasons.<br />
<br />
=== Controversy! ===<br />
<br />
Note that <tt>seq</tt> is the ''only'' way to force evaluation of a value with a function type (except by applying it, which is liable to cause other problems). As such, it is the only reason why Haskell programs are able to distinguish between the following two values:<br />
<br />
<haskell><br />
undefined :: a -> b<br />
const undefined :: a -> b<br />
</haskell><br />
<br />
This violates the principle from lambda calculus of extensionality of functions, or eta-conversion, because <tt>f</tt> and <tt>\x -> f x</tt> are distinct functions, even though they return the same output for ''every'' input. For this reason, <tt>seq</tt>, and this distinction, is sometimes ignored e.g. when assessing the correctness of [[Correctness of short cut fusion|optimisation techniques]] or type class instances.<br />
<br />
== See also ==<br />
<br />
* [http://stackoverflow.com/questions/12687392/why-is-seq-bad Why is seq bad?]<br />
<br />
[[Category:Glossary]]</div>Benmachinehttps://wiki.haskell.org/User:Benmachine/Overqualified_modulesUser:Benmachine/Overqualified modules2014-10-19T15:22:01Z<p>Benmachine: italicising</p>
<hr />
<div>== Overqualified modules ==<br />
<br />
The hierarchical module system was originally proposed as an extension to the Haskell98 standard, and adopted formally in Haskell2010. It is typically regarded as one of the less controversial extensions, because more or less everyone agreed that single-token module names were liable to become a huge tangled mess with everyone stepping on each others' toes.<br />
<br />
=== Data.Data.Data ===<br />
<br />
I lack a little historical context here, since the extension was widespread before I was introduced to Haskell, but I think that the current layout of the module hierarchy is unsatisfactory. Having been given hierarchical modules, Haskellers seem to feel obliged to use them: single-component names are virtually unheard of. Yet in many cases, the additional categorisation seems to add no semantic content whatsoever. What do we learn about a module by its name <tt>Data.Bool</tt> that was not already evident in the <tt>Bool</tt>? Why is the <tt>Functor</tt> type class a piece of <tt>Data</tt> but the closely-related <tt>Applicative</tt> type class a <tt>Control</tt> structure? Why do we have <tt>Data.Monoid</tt> but <tt>Control.Category</tt>?<br />
<br />
=== Redundant specification ===<br />
<br />
There are certainly cases where the additional qualification adds meaning. Writing <hask>import Haskell</hask> at the top of your file seems meaningless, where in <hask>import Haskell.Parser</hask> you have a slightly better idea of what is being requested. However, minimalism is desirable: when adding a component to your module name, ask yourself if it resolves any confusion or prevents any ambiguity. I would argue that in <tt>Codec.Binary.UTF8.Generic</tt>, for example, nearly all of the name is redundant. There is no UTF-8 that is not a binary codec, and arguably the <tt>Generic</tt> component of the name is equally unenlightening. Just name the module <tt>UTF8</tt>, the shortest unambiguous description of its purpose.<br />
<br />
=== Redundant disambiguation ===<br />
<br />
One could argue that keeping module names long reduces the risk of collision. It's true that specifying more information in the module name might reduce the chance of some other module clashing with it, but often people confuse “information content” with “textual length”: clearly, grouping all monad-related modules under <tt>Control.Monad</tt> instead of just <tt>Monad</tt> is not going to stop two implementations of <tt>Reader</tt> from interfering with each other. So keep just the meaningful component of the name: what, after all, could possibly be named <tt>Monad</tt> except for a module housing the <tt>Monad</tt> class and related utility functions? Likewise <tt>Applicative</tt>, <tt>List</tt>, <tt>Exception</tt>, <tt>IO</tt>: all sorts of concepts are clearly going to exist only once in Haskell. Those that don't are no better served being <tt>Control.Monad.Reader</tt> than <tt>Monad.Reader</tt>.<br />
<br />
If you really want to avoid name collisions, take a leaf from syb's book: previously under the hierarchy <tt>Data.Generics</tt>, which not only suffered from <tt>Data</tt>-itis but also adequately described any generic programming mechanism, syb is starting to move over to the new, more specific <tt>Generics.SYB</tt> hierarchy. This drops the useless <tt>Data</tt> prefix and instead uses a component – the name of the package – that is very likely to be unique to this particular design and implementation. We appear to lose some "generality", but in reality the knowledge that you were using SYB in particular was probably already encoded in your program, since other generics libraries will have made different design decisions. The new name also emphasises the position of syb as ''a'' generics library, not ''the'' generics library – on an equal footing with Uniplate and other similar tools.<br />
<br />
=== Internal package politics ===<br />
<br />
Hierarchical modules do make internal structuring of a project easier; one only needs to look at something like Haskore's module list to see that they could clearly not just all be dumped in a single source directory. So that is a legitimate use, but of course there's not necessarily any reason why the internal structure of your project has to be reflected in the external API you provide. If you want twenty helper modules in various tidy subdirectories, fine, but you can probably re-export everything relevant (and it is good design not to export too much) in just a few root modules at the base of your hierarchy. Don't confuse what makes life easy for the library author with what makes things easy for the library user – and don't assume you need to trade one off against the other.<br />
<br />
=== Some syntactical digressions ===<br />
<br />
In addition to the above practical concerns, I also somewhat object to the overuse of the poor little <hask>.</hask> character. For example, one should in principle be able to write a list of all weekdays as <hask>[Monday..]</hask>, but this actually parses as a qualified reference to the Monday module – you'll need to use the marginally uglier <hask>[Monday ..]</hask>. This also demonstrates how the syntax for qualified operators is just plain ugly. It's hard to write and equally hard to read <hask>7 Prelude.+ 8</hask> or, to really rub it in, <hask>f Control.Category.. g</hask>.<br />
<br />
== Conclusion ==<br />
<br />
Hierarchical modules added some much-needed structure to Haskell's module namespace, but should be used sparingly and responsibly to avoid tragic keyboard wear every time I want to <hask>import qualified Text.ParserCombinators.Parsec.Combinator as PCPC</hask>. The policy on how best to name your modules has historically been loose, and the coherence of the module landscape has suffered for it.<br />
<br />
== See also ==<br />
<br />
* [http://www.reddit.com/r/haskell/comments/zdev6/hierarchical_modules_are_frequently_misused/ This article linked on reddit]</div>Benmachinehttps://wiki.haskell.org/StringsStrings2014-03-02T20:38:45Z<p>Benmachine: </p>
<hr />
<div>{{Stub}}<br />
<br />
There are several types of strings that can be used in Haskell programs.<br />
<br />
== String ==<br />
<br />
<hask>String</hask> is the only string type mandated by the language standard, and as such is overwhelmingly the most common, especially for non-performance-sensitive applications. It is simply a type synonym for <hask>[Char]</hask>.<br />
<br />
Pros:<br />
* conceptually simple and easy to use<br />
* interfaces well with other list functions<br />
<br />
Cons:<br />
* massive overhead, up to 4 words per character, which also has speed implications<br />
* not pedantically Unicode-correct in some cases (e.g. there are strings which change length when changing case, so <hask>map toLower</hask> is not accurate in that case)<br />
<br />
== ByteString ==<br />
<br />
<hask>ByteString</hask> is a type defined in the package [http://hackage.haskell.org/package/bytestring bytestring], available from Hackage.<br />
<br />
Bytestrings are sequences of ''bytes'' not characters, and aren't really a text type at all. They are best used for binary data.<br />
<br />
They are low-overhead in space terms and very heavily optimised – they are a key part of writing high-performance code in Haskell.<br />
<br />
=== Data.ByteString.Char8 ===<br />
<br />
TODO<br />
<br />
== Text ==<br />
<br />
For a more efficient processing of text, there is <hask>Text</hask>, defined in the package [http://hackage.haskell.org/package/text text].<br />
<br />
There are two version of <hask>Text</hask>s: lazy and strict.<br />
<br />
<br />
=== Lazy Text ===<br />
<br />
TODO<br />
<br />
<br />
=== Strict Text ===<br />
<br />
TODO<br />
<br />
<br />
== Links ==<br />
<br />
* [[Performance/Strings]]<br />
<br />
* [[Wc]]<br />
<br />
* [https://groups.google.com/forum/?fromgroups#!topic/fa.haskell/QTP6cc6X6w4 Fast number parsing with strict bytestrings]<br />
<br />
* [http://hackage.haskell.org/package/string-conversions string-conversions]; this package provides a simple type class for converting values of different string types into values of other string types.<br />
<br />
* [http://hackage.haskell.org/package/convertible-text convertible-text], a text conversion package ([http://www.mail-archive.com/haskell-cafe@haskell.org/msg97795.html depricated])</div>Benmachinehttps://wiki.haskell.org/PurePure2013-09-15T01:36:05Z<p>Benmachine: Created page with "A function is called '''pure''' if it corresponds to a function in the mathematical sense: it associates each possible input value with an output value, and does nothing else...."</p>
<hr />
<div>A function is called '''pure''' if it corresponds to a function in the mathematical sense: it associates each possible input value with an output value, and does nothing else. In particular,<br />
<br />
* it has no ''side effects'', that is to say, invoking it produces no observable effect other than the result it returns; it cannot also ''e.g.'' write to disk, or print to a screen.<br />
* it does not depend on anything other than its parameters, so when invoked in a different context or at a different time with the same arguments, it will produce the same result.<br />
<br />
A programming language may be called '''purely functional''' if evaluation of expressions is pure.<br />
<br />
There has been some debate in the past as to the precise meaning of these terms. See also:<br />
<br />
* [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.27.7800 What is a Purely Functional Language?] a 1993 paper which presents a proposed formal definition of the concept,<br />
* [http://conal.net/blog/posts/the-c-language-is-purely-functional The C language is purely functional] (some satire intended),<br />
* [http://conal.net/blog/posts/is-haskell-a-purely-functional-language Is Haskell a purely functional language?]<br />
<br />
[[Category:Glossary]]</div>Benmachinehttps://wiki.haskell.org/User:BenmachineUser:Benmachine2013-09-14T21:29:23Z<p>Benmachine: finished this</p>
<hr />
<div>I found a [[User:benmachine/hasktag_bug|bug with the &lt;hask&gt; tag]]. I put it on its own page so it doesn't ruin my user page.<br />
<br />
I wrote a [[User:benmachine/Cont|Cont tutorial]] of sorts.<br />
<br />
I have some objections to [[User:benmachine/Overqualified modules|module overqualification]]<br />
<br />
I wrote an [[User:benmachine/uninstall.sh|uninstall script]] for things cabal installs.</div>Benmachinehttps://wiki.haskell.org/User:Benmachine/Non-strict_semanticsUser:Benmachine/Non-strict semantics2013-09-14T21:29:05Z<p>Benmachine: Redirected page to Non-strict semantics</p>
<hr />
<div>#REDIRECT [[Non-strict semantics]]</div>Benmachinehttps://wiki.haskell.org/User:Benmachine/Non-strict_semanticsUser:Benmachine/Non-strict semantics2013-09-14T21:28:47Z<p>Benmachine: Moved rewrite to main location</p>
<hr />
<div>#REDIRECT Non-strict semantics</div>Benmachinehttps://wiki.haskell.org/Non-strict_semanticsNon-strict semantics2013-09-14T21:28:33Z<p>Benmachine: Rewrote</p>
<hr />
<div>An expression language is said to have [[non-strict semantics]] if expressions can have a value even if some of their subexpressions do not. Haskell is one of the few modern languages to have non-strict semantics by default: nearly every other language has [[strict semantics]], in which if any subexpression fails to have a value, the whole expression fails with it.<br />
<br />
This is one of the most important features in Haskell: it is what allows programs to work with conceptually infinite data structures, and it is why people say that Haskell lets you write your own control structures. It's also one of the motivations behind Haskell being a [[Purity|pure]] language (though there are several other good ones).<br />
<br />
== What? ==<br />
<br />
Any sufficiently capable programming language is ''non-total'', which is to say you can write expressions that do not produce a value: common examples are an exception thrown, an infinite loop, or unproductive recursion, e.g. the following definition in Haskell:<br />
<br />
<haskell><br />
noreturn :: Integer -> Integer<br />
noreturn x = negate (noreturn x)<br />
</haskell><br />
<br />
or the following Python function:<br />
<br />
def noreturn(x):<br />
while True:<br />
x = -x<br />
<br />
return x # not reached<br />
<br />
both fail to produce a value when executed. We say that <tt>noreturn x</tt> is undefined, and write <tt>noreturn x = [[Bottom|⊥]]</tt>.<br />
<br />
In Python the following expression to check if <tt>2</tt> is in some list:<br />
<br />
2 in [2,4,noreturn(5)]<br />
<br />
also fails to have a value, because in order to construct the list, the interpreter tries to work out <tt>noreturn(5)</tt>, which of course doesn't return a value. This is called '''innermost-first''' evaluation: in order to call a function with some arguments, you first have to calculate what all the arguments are, starting from the innermost function call and working outwards. The result is that Python is ''strict'', in the sense that calling any function with an undefined argument produces an undefined value, i.e. <tt>f(⊥) = ⊥</tt>. If your language uses innermost-first evaluation, it correspondingly must have strict semantics.<br />
<br />
In Haskell, an analogous expression:<br />
<br />
<haskell><br />
elem 2 [2, 4, noreturn 5]<br />
</haskell><br />
<br />
in fact has the value <tt>True</tt>. The program does not have to compute <tt>noreturn 5</tt> because it is irrelevant to the overall value of the computation: only the values that are necessary to the result need be computed. This is called '''outermost-first''' evaluation because you first look at the outermost function call, <tt>elem</tt>, to see if it needs to use its arguments, and only if it does do you look at what those arguments are. This means that you can write a function that doesn't look at its argument, so it will return a value even if the argument is <tt>⊥</tt>. Such functions are ''not strict'', i.e. they satisfy <tt>f(⊥) ≠ ⊥</tt>. Practically, this means that Haskell functions need not completely compute their arguments before using them, which is why e.g. <tt>take 3 [1..]</tt> can produce <tt>[1,2,3]</tt> even though it is given a conceptually infinite list.<br />
<br />
Note that outermost-first evaluation is not the only way to have non-strict semantics: a speculative evaluation strategy, that evaluates arguments in parallel with the function in case they are needed later, could also be non-strict, as long as whenever the speculative evaluation failed, the evaluation of the function continued.<br />
<br />
Note also that in order for a function to be truly non-strict, it must return something without inspecting its argument ''at all''. You might think that doesn't sound like a very useful function, but remember that it might be e.g. a partial application: the function <tt>(||) True</tt>, or equivalently <tt>\x -> True || x</tt> does not need to inspect its argument, since <tt>True || x</tt> is always <tt>True</tt>. There are other examples, too: constructors like <tt>Just</tt> wrap their argument without inspecting it, and some other functions apply constructors before looking at the argument, and hence still produce a partial result, e.g. <tt>inits ⊥ = [] : ⊥</tt><br />
<br />
== Why? ==<br />
<br />
The important thing to understand about non-strict semantics is that it is not a performance feature. Non-strict semantics allows your language to only evaluate the things it needs to, but if you write your programs carefully, you'll only compute what is absolutely necessary ''anyway'', so the extra time your program spends working out what should and shouldn't be evaluated is time wasted. For this reason, a very well-optimised strict program will frequently outperform even the fastest non-strict program.<br />
<br />
However, the real and major advantage that non-strictness gives you over strict languages is you get to write cleaner and more composable code. In particular, you can separate ''production'' and ''consumption'' of data: don't know how many prime numbers you're going to need? Just make `primes` a list of ''all'' prime numbers, and then which ones actually get ''generated'' depends on how you use them in the rest of your code. By contrast, writing code in a strict language that constructs a data structure in response to demand usually will require first-class functions and/or a lot of manual hoop-jumping to make it all behave itself.<br />
<br />
Consider the following Haskell function definition:<br />
<br />
<haskell><br />
any :: (a -> Bool) -> [a] -> Bool<br />
any p = or . map p<br />
</haskell><br />
<br />
Here, <tt>map p</tt> replaces each element of the list with a boolean value representing whether or not that element satisfied <tt>p</tt>, then <tt>or</tt> checks if any of the booleans were <tt>True</tt>. Overall, then, <tt>any p xs</tt> tells you whether or not <tt>p x</tt> is <tt>True</tt> for any <tt>x</tt> in <tt>xs</tt>.<br />
<br />
Naively, it seems like this would be inefficient: first <tt>map</tt> processes the whole list, and then <tt>or</tt> finds any <tt>True</tt>s – but if the very first item of the list satisfies <tt>p</tt>, then you really didn't need to map over all the others.<br />
<br />
But in a non-strict context, even if both <tt>or</tt> and <tt>map</tt> are written completely naïvely, when <tt>or</tt> gets to the first <tt>True</tt> it stops asking for any more booleans, so <tt>map</tt> doesn't need to produce any more of them, and none of the rest of the list is visited.<br />
<br />
== But that's so weird! ==<br />
<br />
Not really! In non-strict languages you typically have evaluation driven by need, whereas in strict languages you have evaluation driven by function application. But functions are already for abstraction, so they end up serving a sort of dual purpose; meanwhile ordinary values can't really be used for abstraction, except if you know you're going to use their value at least once. If you don't, you have to wrap your value in a function that doesn't take any arguments, or in certain type systems where that doesn't make sense as a concept, you have to use a function that takes a single, boring argument, that it then ignores. You then have to duplicate the work if you want to use it twice, or else write some sort of caching, probably using mutable variables. On top of all that, you decide that function application isn't even the only method of driving evaluation, because you also need if-statements, loops, and other control structures that you have to bake right into the fabric of your language.<br />
<br />
In a strict langauge, to get the short-circuiting behaviour of <tt>any</tt> described in the previous section, you'd have little choice but to write out the whole recursion explicitly:<br />
<br />
<haskell><br />
any p [] = False<br />
any p (x:xs)<br />
| p x = True<br />
| otherwise = any p xs<br />
</haskell><br />
<br />
since in strict languages only builtin control structures can decide whether some bit of code gets executed or not, ordinary functions like <tt>or</tt> can't. You essentially duplicate the code of <tt>map</tt> iterating over the list and applying a function, and <tt>or</tt> folding the list with a binary operation.<br />
<br />
Meanwhile, in Haskell, functions are precisely for abstraction with parameters, and for abstraction without parameters, ordinary values suffice, whether you end up using them or not. All code, inside or outside functions, gets run when you need it and doesn't when you don't. You can easily write control structures as ordinary code:<br />
<br />
<haskell><br />
ifThenElse :: Bool -> a -> a -> a<br />
ifThenElse True x _ = x<br />
ifThenElse False _ y = y<br />
</haskell><br />
<br />
and this allows all sorts of interesting patterns to be abstracted in an incredibly lightweight fashion. Labelled for-loops are a ''library'' in Haskell, rather than requiring special syntax and language support.<br />
<br />
== How do I stop it? ==<br />
<br />
As mentioned above, non-strictness can hurt performance, e.g. if a result is definitely going to be needed later, you might as well evaluate it now, to avoid having to hold on to all the data that goes into it. Fortunately, the Haskell designers were aware of these problems and introduced a loophole or two so that we could force our programs to be strict when necessary: see [[Performance/Strictness]] and [[seq]].<br />
<br />
[[Category:Glossary]]</div>Benmachinehttps://wiki.haskell.org/User:Benmachine/Non-strict_semanticsUser:Benmachine/Non-strict semantics2013-09-14T20:25:22Z<p>Benmachine: </p>
<hr />
<div>An expression language is said to have [[non-strict semantics]] if expressions can have a value even if some of their subexpressions do not. Haskell is one of the few modern languages to have non-strict semantics by default: nearly every other language has [[strict semantics]], in which if any subexpression fails to have a value, the whole expression fails with it.<br />
<br />
This is one of the most important features in Haskell: it is what allows programs to work with conceptually infinite data structures, and it is why people say that Haskell lets you write your own control structures. It's also one of the motivations behind Haskell being a [[Purity|pure]] language (though there are several other good ones).<br />
<br />
== What? ==<br />
<br />
Any sufficiently capable programming language is ''non-total'', which is to say you can write expressions that do not produce a value: common examples are an exception thrown, an infinite loop, or unproductive recursion, e.g. the following definition in Haskell:<br />
<br />
<haskell><br />
noreturn :: Integer -> Integer<br />
noreturn x = negate (noreturn x)<br />
</haskell><br />
<br />
or the following Python function:<br />
<br />
def noreturn(x):<br />
while True:<br />
x = -x<br />
<br />
return x # not reached<br />
<br />
both fail to produce a value when executed. We say that <tt>noreturn x</tt> is undefined, and write <tt>noreturn x = [[Bottom|⊥]]</tt>.<br />
<br />
In Python the following expression to check if <tt>2</tt> is in some list:<br />
<br />
2 in [2,4,noreturn(5)]<br />
<br />
also fails to have a value, because in order to construct the list, the interpreter tries to work out <tt>noreturn(5)</tt>, which of course doesn't return a value. This is called '''innermost-first''' evaluation: in order to call a function with some arguments, you first have to calculate what all the arguments are, starting from the innermost function call and working outwards. The result is that Python is ''strict'', in the sense that calling any function with an undefined argument produces an undefined value, i.e. <tt>f(⊥) = ⊥</tt>. If your language uses innermost-first evaluation, it correspondingly must have strict semantics.<br />
<br />
In Haskell, an analogous expression:<br />
<br />
<haskell><br />
elem 2 [2, 4, noreturn 5]<br />
</haskell><br />
<br />
in fact has the value <tt>True</tt>. The program does not have to compute <tt>noreturn 5</tt> because it is irrelevant to the overall value of the computation: only the values that are necessary to the result need be computed. This is called '''outermost-first''' evaluation because you first look at the outermost function call, <tt>elem</tt>, to see if it needs to use its arguments, and only if it does do you look at what those arguments are. This means that you can write a function that doesn't look at its argument, so it will return a value even if the argument is <tt>⊥</tt>. Such functions are ''not strict'', i.e. they satisfy <tt>f(⊥) ≠ ⊥</tt>. Practically, this means that Haskell functions need not completely compute their arguments before using them, which is why e.g. <tt>take 3 [1..]</tt> can produce <tt>[1,2,3]</tt> even though it is given a conceptually infinite list.<br />
<br />
Note that outermost-first evaluation is not the only way to have non-strict semantics: a speculative evaluation strategy, that evaluates arguments in parallel with the function in case they are needed later, could also be non-strict, as long as whenever the speculative evaluation failed, the evaluation of the function continued.<br />
<br />
Note also that in order for a function to be truly non-strict, it must return something without inspecting its argument ''at all''. You might think that doesn't sound like a very useful function, but remember that it might be e.g. a partial application: the function <tt>(||) True</tt>, or equivalently <tt>\x -> True || x</tt> does not need to inspect its argument, since <tt>True || x</tt> is always <tt>True</tt>. There are other examples, too: constructors like <tt>Just</tt> wrap their argument without inspecting it, and some other functions apply constructors before looking at the argument, and hence still produce a partial result, e.g. <tt>inits ⊥ = [] : ⊥</tt><br />
<br />
== Why? ==<br />
<br />
The important thing to understand about non-strict semantics is that it is not a performance feature. Non-strict semantics allows your language to only evaluate the things it needs to, but if you write your programs carefully, you'll only compute what is absolutely necessary ''anyway'', so the extra time your program spends working out what should and shouldn't be evaluated is time wasted. For this reason, a very well-optimised strict program will frequently outperform even the fastest non-strict program.<br />
<br />
However, the real and major advantage that non-strictness gives you over strict languages is you get to write cleaner and more composable code. In particular, you can separate ''production'' and ''consumption'' of data: don't know how many prime numbers you're going to need? Just make `primes` a list of ''all'' prime numbers, and then which ones actually get ''generated'' depends on how you use them in the rest of your code. By contrast, writing code in a strict language that constructs a data structure in response to demand usually will require first-class functions and/or a lot of manual hoop-jumping to make it all behave itself.<br />
<br />
Consider the following Haskell function definition:<br />
<br />
<haskell><br />
any :: (a -> Bool) -> [a] -> Bool<br />
any p = or . map p<br />
</haskell><br />
<br />
Here, <tt>map p</tt> replaces each element of the list with a boolean value representing whether or not that element satisfied <tt>p</tt>, then <tt>or</tt> checks if any of the booleans were <tt>True</tt>. Overall, then, <tt>any p xs</tt> tells you whether or not <tt>p x</tt> is <tt>True</tt> for any <tt>x</tt> in <tt>xs</tt>.<br />
<br />
Naively, it seems like this would be inefficient: first <tt>map</tt> processes the whole list, and then <tt>or</tt> finds any <tt>True</tt>s – but if the very first item of the list satisfies <tt>p</tt>, then you really didn't need to map over all the others.<br />
<br />
But in a non-strict context, even if both <tt>or</tt> and <tt>map</tt> are written completely naïvely, when <tt>or</tt> gets to the first <tt>True</tt> it stops asking for any more booleans, so <tt>map</tt> doesn't need to produce any more of them, and none of the rest of the list is visited.<br />
<br />
== But that's so weird! ==<br />
<br />
Not really! In non-strict languages you typically have evaluation driven by need, whereas in strict languages you have evaluation driven by function application. But functions are already for abstraction, so they end up serving a sort of dual purpose; meanwhile ordinary values can't really be used for abstraction, except if you know you're going to use their value at least once. If you don't, you have to wrap your value in a function that doesn't take any arguments, or in certain type systems where that doesn't make sense as a concept, you have to use a function that takes a single, boring argument, that it then ignores. You then have to duplicate the work if you want to use it twice, or else write some sort of caching, probably using mutable variables. On top of all that, you decide that function application isn't even the only method of driving evaluation, because you also need if-statements, loops, and other control structures that you have to bake right into the fabric of your language.<br />
<br />
In a strict langauge, to get the short-circuiting behaviour of <tt>any</tt> described in the previous section, you'd have little choice but to write out the whole recursion explicitly:<br />
<br />
<haskell><br />
any p [] = False<br />
any p (x:xs)<br />
| p x = True<br />
| otherwise = any p xs<br />
</haskell><br />
<br />
since in strict languages only builtin control structures can decide whether some bit of code gets executed or not, ordinary functions like <tt>or</tt> can't. You essentially duplicate the code of <tt>map</tt> iterating over the list and applying a function, and <tt>or</tt> folding the list with a binary operation.<br />
<br />
Meanwhile, in Haskell, functions are precisely for abstraction with parameters, and for abstraction without parameters, ordinary values suffice, whether you end up using them or not. All code, inside or outside functions, gets run when you need it and doesn't when you don't. You can easily write control structures as ordinary code:<br />
<br />
<haskell><br />
ifThenElse :: Bool -> a -> a -> a<br />
ifThenElse True x _ = x<br />
ifThenElse False _ y = y<br />
</haskell><br />
<br />
and this allows all sorts of interesting patterns to be abstracted in an incredibly lightweight fashion. Labelled for-loops are a ''library'' in Haskell, rather than requiring special syntax and language support.<br />
<br />
== How do I stop it? ==<br />
<br />
As mentioned above, non-strictness can hurt performance, e.g. if a result is definitely going to be needed later, you might as well evaluate it now, to avoid having to hold on to all the data that goes into it. Fortunately, the Haskell designers were aware of these problems and introduced a loophole or two so that we could force our programs to be strict when necessary: see [[Performance/Strictness]] and [[seq]].</div>Benmachinehttps://wiki.haskell.org/User:Benmachine/Non-strict_semanticsUser:Benmachine/Non-strict semantics2013-09-14T20:07:27Z<p>Benmachine: Why non-strictness matters</p>
<hr />
<div>An expression language is said to have [[non-strict semantics]] if expressions can have a value even if some of their subexpressions do not. Haskell is one of the few modern languages to have non-strict semantics by default: nearly every other language has [[strict semantics]], in which if any subexpression fails to have a value, the whole expression fails with it.<br />
<br />
This is one of the most important features in Haskell: it is what allows programs to work with conceptually infinite data structures, and it is why people say that Haskell lets you write your own control structures. It's also one of the motivations behind Haskell being a [[Purity|pure]] language (though there are several other good ones).<br />
<br />
== What? ==<br />
<br />
Any sufficiently capable programming language is ''non-total'', which is to say you can write expressions that do not produce a value: common examples are an exception thrown, an infinite loop, or unproductive recursion, e.g. the following definition in Haskell:<br />
<br />
<haskell><br />
noreturn :: Integer -> Integer<br />
noreturn x = negate (noreturn x)<br />
</haskell><br />
<br />
or the following Python function:<br />
<br />
def noreturn(x):<br />
while True:<br />
x = -x<br />
<br />
return x # not reached<br />
<br />
both fail to produce a value when executed. We say that <tt>noreturn x</tt> is undefined, and write <tt>noreturn x = [[Bottom|⊥]]</tt>.<br />
<br />
In Python the following expression to check if <tt>2</tt> is in some list:<br />
<br />
2 in [2,4,noreturn(5)]<br />
<br />
also fails to have a value, because in order to construct the list, the interpreter tries to work out <tt>noreturn(5)</tt>, which of course doesn't return a value. This is called '''innermost-first''' evaluation: in order to call a function with some arguments, you first have to calculate what all the arguments are, starting from the innermost function call and working outwards. The result is that Python is ''strict'', in the sense that calling any function with an undefined argument produces an undefined value, i.e. <tt>f(⊥) = ⊥</tt>. If your language uses innermost-first evaluation, it correspondingly must have strict semantics.<br />
<br />
In Haskell, an analogous expression:<br />
<br />
<haskell><br />
elem 2 [2, 4, noreturn 5]<br />
</haskell><br />
<br />
in fact has the value <tt>True</tt>. The program does not have to compute <tt>noreturn 5</tt> because it is irrelevant to the overall value of the computation: only the values that are necessary to the result need be computed. This is called '''outermost-first''' evaluation because you first look at the outermost function call, <tt>elem</tt>, to see if it needs to use its arguments, and only if it does do you look at what those arguments are. This means that you can write a function that doesn't look at its argument, so it will return a value even if the argument is <tt>⊥</tt>. Such functions are ''not strict'', i.e. they satisfy <tt>f(⊥) ≠ ⊥</tt>. Practically, this means that Haskell functions need not completely compute their arguments before using them, which is why e.g. <tt>take 3 [1..]</tt> can produce <tt>[1,2,3]</tt> even though it is given a conceptually infinite list.<br />
<br />
Note that outermost-first evaluation is not the only way to have non-strict semantics: a speculative evaluation strategy, that evaluates arguments in parallel with the function in case they are needed later, could also be non-strict, as long as whenever the speculative evaluation failed, the evaluation of the function continued.<br />
<br />
Note also that in order for a function to be truly non-strict, it must return something without inspecting its argument ''at all''. You might think that doesn't sound like a very useful function, but remember that it might be e.g. a partial application: the function <tt>(||) True</tt>, or equivalently <tt>\x -> True || x</tt> does not need to inspect its argument, since <tt>True || x</tt> is always <tt>True</tt>. There are other examples, too: constructors like <tt>Just</tt> wrap their argument without inspecting it, and some other functions apply constructors before looking at the argument, and hence still produce a partial result, e.g. <tt>inits ⊥ = [] : ⊥</tt><br />
<br />
== Why? ==<br />
<br />
The important thing to understand about non-strict semantics is that it is not a performance feature. Non-strict semantics allows your language to only evaluate the things it needs to, but if you write your programs carefully, you'll only compute what is absolutely necessary ''anyway'', so the extra time your program spends working out what should and shouldn't be evaluated is time wasted. For this reason, a very well-optimised strict program will frequently outperform even the fastest non-strict program.<br />
<br />
However, the real and major advantage that non-strictness gives you over strict languages is you get to write cleaner and more composable code. In particular, you can separate ''production'' and ''consumption'' of data: don't know how many prime numbers you're going to need? Just make `primes` a list of ''all'' prime numbers, and then which ones actually get ''generated'' depends on how you use them in the rest of your code. By contrast, writing code in a strict language that constructs a data structure in response to demand usually will require first-class functions and/or a lot of manual hoop-jumping to make it all behave itself.<br />
<br />
Consider the following Haskell function definition:<br />
<br />
<haskell><br />
any :: (a -> Bool) -> [a] -> Bool<br />
any p = or . map p<br />
</haskell><br />
<br />
Because <tt>or</tt> uses non-strictness to stop at the first <tt>True</tt> in the input, <tt>map</tt> doesn't even need to know that only the first half of the list might be needed. We can write <tt>map</tt> in the completely straightforward and obviously correct way, and still have it interact well with <tt>or</tt> in this way; <tt>map</tt> produces data, <tt>or</tt> consumes it, and the two are properly decoupled.<br />
<br />
In a strict langauge, you'd have to write the recursion out manually:<br />
<br />
<haskell><br />
any p [] = False<br />
any p (x:xs)<br />
| p x = True<br />
| otherwise = any p xs<br />
</haskell><br />
<br />
since in strict languages only builtin control structures can decide whether some bit of code gets executed or not, ordinary functions like <tt>or</tt> can't.<br />
<br />
It's this additional power that Haskell has that leads people to say you can define your own control structures as normal Haskell functions, which allows all sorts of interesting patterns to be abstracted in an incredibly lightweight fashion. Labelled for-loops are a ''library'' in Haskell, rather than requiring special syntax and language support.<br />
<br />
== How do I stop it? ==<br />
<br />
As mentioned above, non-strictness can hurt performance, e.g. if a result is definitely going to be needed later, you might as well evaluate it now, to avoid having to hold on to all the data that goes into it. Fortunately, the Haskell designers were aware of these problems and introduced a loophole or two so that we could force our programs to be strict when necessary: see [[Performance/Strictness]] and [[seq]].</div>Benmachinehttps://wiki.haskell.org/User:Benmachine/Non-strict_semanticsUser:Benmachine/Non-strict semantics2013-09-14T20:06:51Z<p>Benmachine: Upgrade all the headings from h3s to h2s</p>
<hr />
<div>An expression language is said to have [[non-strict semantics]] if expressions can have a value even if some of their subexpressions do not. Haskell is one of the few modern languages to have non-strict semantics by default: nearly every other language has [[strict semantics]], in which if any subexpression fails to have a value, the whole expression fails with it.<br />
<br />
== What? ==<br />
<br />
Any sufficiently capable programming language is ''non-total'', which is to say you can write expressions that do not produce a value: common examples are an exception thrown, an infinite loop, or unproductive recursion, e.g. the following definition in Haskell:<br />
<br />
<haskell><br />
noreturn :: Integer -> Integer<br />
noreturn x = negate (noreturn x)<br />
</haskell><br />
<br />
or the following Python function:<br />
<br />
def noreturn(x):<br />
while True:<br />
x = -x<br />
<br />
return x # not reached<br />
<br />
both fail to produce a value when executed. We say that <tt>noreturn x</tt> is undefined, and write <tt>noreturn x = [[Bottom|⊥]]</tt>.<br />
<br />
In Python the following expression to check if <tt>2</tt> is in some list:<br />
<br />
2 in [2,4,noreturn(5)]<br />
<br />
also fails to have a value, because in order to construct the list, the interpreter tries to work out <tt>noreturn(5)</tt>, which of course doesn't return a value. This is called '''innermost-first''' evaluation: in order to call a function with some arguments, you first have to calculate what all the arguments are, starting from the innermost function call and working outwards. The result is that Python is ''strict'', in the sense that calling any function with an undefined argument produces an undefined value, i.e. <tt>f(⊥) = ⊥</tt>. If your language uses innermost-first evaluation, it correspondingly must have strict semantics.<br />
<br />
In Haskell, an analogous expression:<br />
<br />
<haskell><br />
elem 2 [2, 4, noreturn 5]<br />
</haskell><br />
<br />
in fact has the value <tt>True</tt>. The program does not have to compute <tt>noreturn 5</tt> because it is irrelevant to the overall value of the computation: only the values that are necessary to the result need be computed. This is called '''outermost-first''' evaluation because you first look at the outermost function call, <tt>elem</tt>, to see if it needs to use its arguments, and only if it does do you look at what those arguments are. This means that you can write a function that doesn't look at its argument, so it will return a value even if the argument is <tt>⊥</tt>. Such functions are ''not strict'', i.e. they satisfy <tt>f(⊥) ≠ ⊥</tt>. Practically, this means that Haskell functions need not completely compute their arguments before using them, which is why e.g. <tt>take 3 [1..]</tt> can produce <tt>[1,2,3]</tt> even though it is given a conceptually infinite list.<br />
<br />
Note that outermost-first evaluation is not the only way to have non-strict semantics: a speculative evaluation strategy, that evaluates arguments in parallel with the function in case they are needed later, could also be non-strict, as long as whenever the speculative evaluation failed, the evaluation of the function continued.<br />
<br />
Note also that in order for a function to be truly non-strict, it must return something without inspecting its argument ''at all''. You might think that doesn't sound like a very useful function, but remember that it might be e.g. a partial application: the function <tt>(||) True</tt>, or equivalently <tt>\x -> True || x</tt> does not need to inspect its argument, since <tt>True || x</tt> is always <tt>True</tt>. There are other examples, too: constructors like <tt>Just</tt> wrap their argument without inspecting it, and some other functions apply constructors before looking at the argument, and hence still produce a partial result, e.g. <tt>inits ⊥ = [] : ⊥</tt><br />
<br />
== Why? ==<br />
<br />
The important thing to understand about non-strict semantics is that it is not a performance feature. Non-strict semantics allows your language to only evaluate the things it needs to, but if you write your programs carefully, you'll only compute what is absolutely necessary ''anyway'', so the extra time your program spends working out what should and shouldn't be evaluated is time wasted. For this reason, a very well-optimised strict program will frequently outperform even the fastest non-strict program.<br />
<br />
However, the real and major advantage that non-strictness gives you over strict languages is you get to write cleaner and more composable code. In particular, you can separate ''production'' and ''consumption'' of data: don't know how many prime numbers you're going to need? Just make `primes` a list of ''all'' prime numbers, and then which ones actually get ''generated'' depends on how you use them in the rest of your code. By contrast, writing code in a strict language that constructs a data structure in response to demand usually will require first-class functions and/or a lot of manual hoop-jumping to make it all behave itself.<br />
<br />
Consider the following Haskell function definition:<br />
<br />
<haskell><br />
any :: (a -> Bool) -> [a] -> Bool<br />
any p = or . map p<br />
</haskell><br />
<br />
Because <tt>or</tt> uses non-strictness to stop at the first <tt>True</tt> in the input, <tt>map</tt> doesn't even need to know that only the first half of the list might be needed. We can write <tt>map</tt> in the completely straightforward and obviously correct way, and still have it interact well with <tt>or</tt> in this way; <tt>map</tt> produces data, <tt>or</tt> consumes it, and the two are properly decoupled.<br />
<br />
In a strict langauge, you'd have to write the recursion out manually:<br />
<br />
<haskell><br />
any p [] = False<br />
any p (x:xs)<br />
| p x = True<br />
| otherwise = any p xs<br />
</haskell><br />
<br />
since in strict languages only builtin control structures can decide whether some bit of code gets executed or not, ordinary functions like <tt>or</tt> can't.<br />
<br />
It's this additional power that Haskell has that leads people to say you can define your own control structures as normal Haskell functions, which allows all sorts of interesting patterns to be abstracted in an incredibly lightweight fashion. Labelled for-loops are a ''library'' in Haskell, rather than requiring special syntax and language support.<br />
<br />
== How do I stop it? ==<br />
<br />
As mentioned above, non-strictness can hurt performance, e.g. if a result is definitely going to be needed later, you might as well evaluate it now, to avoid having to hold on to all the data that goes into it. Fortunately, the Haskell designers were aware of these problems and introduced a loophole or two so that we could force our programs to be strict when necessary: see [[Performance/Strictness]] and [[seq]].</div>Benmachinehttps://wiki.haskell.org/User:Benmachine/Non-strict_semanticsUser:Benmachine/Non-strict semantics2013-09-14T18:02:33Z<p>Benmachine: /* What? */</p>
<hr />
<div>An expression language is said to have [[non-strict semantics]] if expressions can have a value even if some of their subexpressions do not. Haskell is one of the few modern languages to have non-strict semantics by default: nearly every other language has [[strict semantics]], in which if any subexpression fails to have a value, the whole expression fails with it.<br />
<br />
=== What? ===<br />
<br />
Any sufficiently capable programming language is ''non-total'', which is to say you can write expressions that do not produce a value: common examples are an exception thrown, an infinite loop, or unproductive recursion, e.g. the following definition in Haskell:<br />
<br />
<haskell><br />
noreturn :: Integer -> Integer<br />
noreturn x = negate (noreturn x)<br />
</haskell><br />
<br />
or the following Python function:<br />
<br />
def noreturn(x):<br />
while True:<br />
x = -x<br />
<br />
return x # not reached<br />
<br />
both fail to produce a value when executed. We say that <tt>noreturn x</tt> is undefined, and write <tt>noreturn x = [[Bottom|⊥]]</tt>.<br />
<br />
In Python the following expression to check if <tt>2</tt> is in some list:<br />
<br />
2 in [2,4,noreturn(5)]<br />
<br />
also fails to have a value, because in order to construct the list, the interpreter tries to work out <tt>noreturn(5)</tt>, which of course doesn't return a value. This is called '''innermost-first''' evaluation: in order to call a function with some arguments, you first have to calculate what all the arguments are, starting from the innermost function call and working outwards. The result is that Python is ''strict'', in the sense that calling any function with an undefined argument produces an undefined value, i.e. <tt>f(⊥) = ⊥</tt>. If your language uses innermost-first evaluation, it correspondingly must have strict semantics.<br />
<br />
In Haskell, an analogous expression:<br />
<br />
<haskell><br />
elem 2 [2, 4, noreturn 5]<br />
</haskell><br />
<br />
in fact has the value <tt>True</tt>. The program does not have to compute <tt>noreturn 5</tt> because it is irrelevant to the overall value of the computation: only the values that are necessary to the result need be computed. This is called '''outermost-first''' evaluation because you first look at the outermost function call, <tt>elem</tt>, to see if it needs to use its arguments, and only if it does do you look at what those arguments are. This means that you can write a function that doesn't look at its argument, so it will return a value even if the argument is <tt>⊥</tt>. Such functions are ''not strict'', i.e. they satisfy <tt>f(⊥) ≠ ⊥</tt>. Practically, this means that Haskell functions need not completely compute their arguments before using them, which is why e.g. <tt>take 3 [1..]</tt> can produce <tt>[1,2,3]</tt> even though it is given a conceptually infinite list.<br />
<br />
Note that outermost-first evaluation is not the only way to have non-strict semantics: a speculative evaluation strategy, that evaluates arguments in parallel with the function in case they are needed later, could also be non-strict, as long as whenever the speculative evaluation failed, the evaluation of the function continued.<br />
<br />
Note also that in order for a function to be truly non-strict, it must return something without inspecting its argument ''at all''. You might think that doesn't sound like a very useful function, but remember that it might be e.g. a partial application: the function <tt>(||) True</tt>, or equivalently <tt>\x -> True || x</tt> does not need to inspect its argument, since <tt>True || x</tt> is always <tt>True</tt>. There are other examples, too: constructors like <tt>Just</tt> wrap their argument without inspecting it, and some other functions apply constructors before looking at the argument, and hence still produce a partial result, e.g. <tt>inits ⊥ = [] : ⊥</tt><br />
<br />
=== Why? ===<br />
<br />
The important thing to understand about non-strict semantics is that it is not a performance feature. Non-strict semantics allows your language to only evaluate the things it needs to, but if you write your programs carefully, you'll only compute what is absolutely necessary ''anyway'', so the extra time your program spends working out what should and shouldn't be evaluated is time wasted. For this reason, a very well-optimised strict program will frequently outperform even the fastest non-strict program.<br />
<br />
However, the real and major advantage that non-strictness gives you over strict languages is you get to write cleaner and more composable code. In particular, you can separate ''production'' and ''consumption'' of data: don't know how many prime numbers you're going to need? Just make `primes` a list of ''all'' prime numbers, and then which ones actually get ''generated'' depends on how you use them in the rest of your code. By contrast, writing code in a strict language that constructs a data structure in response to demand usually will require first-class functions and/or a lot of manual hoop-jumping to make it all behave itself.<br />
<br />
Consider the following Haskell function definition:<br />
<br />
<haskell><br />
any :: (a -> Bool) -> [a] -> Bool<br />
any p = or . map p<br />
</haskell><br />
<br />
Because <tt>or</tt> uses non-strictness to stop at the first <tt>True</tt> in the input, <tt>map</tt> doesn't even need to know that only the first half of the list might be needed. We can write <tt>map</tt> in the completely straightforward and obviously correct way, and still have it interact well with <tt>or</tt> in this way; <tt>map</tt> produces data, <tt>or</tt> consumes it, and the two are properly decoupled.<br />
<br />
In a strict langauge, you'd have to write the recursion out manually:<br />
<br />
<haskell><br />
any p [] = False<br />
any p (x:xs)<br />
| p x = True<br />
| otherwise = any p xs<br />
</haskell><br />
<br />
since in strict languages only builtin control structures can decide whether some bit of code gets executed or not, ordinary functions like <tt>or</tt> can't.<br />
<br />
It's this additional power that Haskell has that leads people to say you can define your own control structures as normal Haskell functions, which allows all sorts of interesting patterns to be abstracted in an incredibly lightweight fashion. Labelled for-loops are a ''library'' in Haskell, rather than requiring special syntax and language support.<br />
<br />
=== How do I stop it? ===<br />
<br />
As mentioned above, non-strictness can hurt performance, e.g. if a result is definitely going to be needed later, you might as well evaluate it now, to avoid having to hold on to all the data that goes into it. Fortunately, the Haskell designers were aware of these problems and introduced a loophole or two so that we could force our programs to be strict when necessary: see [[Performance/Strictness]] and [[seq]].</div>Benmachinehttps://wiki.haskell.org/User:Benmachine/Non-strict_semanticsUser:Benmachine/Non-strict semantics2013-09-14T18:01:29Z<p>Benmachine: /* What? */</p>
<hr />
<div>An expression language is said to have [[non-strict semantics]] if expressions can have a value even if some of their subexpressions do not. Haskell is one of the few modern languages to have non-strict semantics by default: nearly every other language has [[strict semantics]], in which if any subexpression fails to have a value, the whole expression fails with it.<br />
<br />
=== What? ===<br />
<br />
Any sufficiently capable programming language is ''non-total'', which is to say you can write expressions that do not produce a value: common examples are an exception thrown, an infinite loop, or unproductive recursion, e.g. the following definition in Haskell:<br />
<br />
<haskell><br />
noreturn :: Integer -> Integer<br />
noreturn x = negate (noreturn x)<br />
</haskell><br />
<br />
or the following Python function:<br />
<br />
def noreturn(x):<br />
while True:<br />
x = -x<br />
<br />
return x # not reached<br />
<br />
both fail to produce a value when executed. We say that <tt>noreturn x</tt> is undefined, and write <tt>noreturn x = [[Bottom|⊥]]</tt>.<br />
<br />
In Python the following expression to check if <tt>2</tt> is in some list:<br />
<br />
2 in [2,4,noreturn(5)]<br />
<br />
also fails to have a value, because in order to construct the list, the interpreter tries to work out <tt>noreturn(5)</tt>, which of course doesn't return a value. This is called '''innermost-first''' evaluation: in order to call a function with some arguments, you first have to calculate what all the arguments are, starting from the innermost function call and working outwards. The result is that Python is ''strict'', in the sense that calling any function with an undefined argument produces an undefined value, i.e. <tt>f(⊥) = ⊥</tt>. If your language uses innermost-first evaluation, it correspondingly must have strict semantics.<br />
<br />
In Haskell, an analogous expression:<br />
<br />
<haskell><br />
elem 2 [2, 4, noreturn 5]<br />
</haskell><br />
<br />
in fact has the value <tt>True</tt>. The program does not have to compute <tt>noreturn 5</tt> because it is irrelevant to the overall value of the computation: only the values that are necessary to the result need be computed. This is called '''outermost-first''' evaluation because you first look at the outermost function call, <tt>elem</tt>, to see if it needs to use its arguments, and only if it does do you look at what those arguments are. This means that you can write a function that doesn't look at its argument, so it will return a value even if the argument is <tt>⊥</tt>. Such functions are ''not strict'', i.e. they satisfy <tt>f(⊥) ≠ ⊥</tt>. Practically, this means that Haskell functions need not completely compute their arguments before using them, which is why e.g. <tt>take 3 [1..]</tt> can produce <tt>[1,2,3]</tt> even though it is given a conceptually infinite list.<br />
<br />
Note that outermost-first evaluation is not the only way to have non-strict semantics: a speculative evaluation strategy, that evaluates arguments in parallel with the function in case they are needed later, could also be non-strict, as long as whenever the speculative evaluation failed, the evaluation of the function continued.<br />
<br />
Note also that in order for a function to be truly non-strict, it must return something without inspecting its argument ''at all''. You might think that doesn't sound like a very useful function, but remember that it might be e.g. a partial application: the function <tt>(||) True</tt>, or equivalently <tt>\x -> True || x</tt> does not need to inspect its argument, since <tt>True || x</tt> is always <tt>True</tt>. There are other examples, too: constructors like <tt>Just</tt> wrap their argument without inspecting it, and some other functions apply constructors ''before'' looking at the argument, and hence still produce a partial result, e.g. <tt>inits ⊥ = [] : ⊥</tt><br />
<br />
=== Why? ===<br />
<br />
The important thing to understand about non-strict semantics is that it is not a performance feature. Non-strict semantics allows your language to only evaluate the things it needs to, but if you write your programs carefully, you'll only compute what is absolutely necessary ''anyway'', so the extra time your program spends working out what should and shouldn't be evaluated is time wasted. For this reason, a very well-optimised strict program will frequently outperform even the fastest non-strict program.<br />
<br />
However, the real and major advantage that non-strictness gives you over strict languages is you get to write cleaner and more composable code. In particular, you can separate ''production'' and ''consumption'' of data: don't know how many prime numbers you're going to need? Just make `primes` a list of ''all'' prime numbers, and then which ones actually get ''generated'' depends on how you use them in the rest of your code. By contrast, writing code in a strict language that constructs a data structure in response to demand usually will require first-class functions and/or a lot of manual hoop-jumping to make it all behave itself.<br />
<br />
Consider the following Haskell function definition:<br />
<br />
<haskell><br />
any :: (a -> Bool) -> [a] -> Bool<br />
any p = or . map p<br />
</haskell><br />
<br />
Because <tt>or</tt> uses non-strictness to stop at the first <tt>True</tt> in the input, <tt>map</tt> doesn't even need to know that only the first half of the list might be needed. We can write <tt>map</tt> in the completely straightforward and obviously correct way, and still have it interact well with <tt>or</tt> in this way; <tt>map</tt> produces data, <tt>or</tt> consumes it, and the two are properly decoupled.<br />
<br />
In a strict langauge, you'd have to write the recursion out manually:<br />
<br />
<haskell><br />
any p [] = False<br />
any p (x:xs)<br />
| p x = True<br />
| otherwise = any p xs<br />
</haskell><br />
<br />
since in strict languages only builtin control structures can decide whether some bit of code gets executed or not, ordinary functions like <tt>or</tt> can't.<br />
<br />
It's this additional power that Haskell has that leads people to say you can define your own control structures as normal Haskell functions, which allows all sorts of interesting patterns to be abstracted in an incredibly lightweight fashion. Labelled for-loops are a ''library'' in Haskell, rather than requiring special syntax and language support.<br />
<br />
=== How do I stop it? ===<br />
<br />
As mentioned above, non-strictness can hurt performance, e.g. if a result is definitely going to be needed later, you might as well evaluate it now, to avoid having to hold on to all the data that goes into it. Fortunately, the Haskell designers were aware of these problems and introduced a loophole or two so that we could force our programs to be strict when necessary: see [[Performance/Strictness]] and [[seq]].</div>Benmachinehttps://wiki.haskell.org/User:Benmachine/Non-strict_semanticsUser:Benmachine/Non-strict semantics2013-09-14T17:53:33Z<p>Benmachine: </p>
<hr />
<div>An expression language is said to have [[non-strict semantics]] if expressions can have a value even if some of their subexpressions do not. Haskell is one of the few modern languages to have non-strict semantics by default: nearly every other language has [[strict semantics]], in which if any subexpression fails to have a value, the whole expression fails with it.<br />
<br />
=== What? ===<br />
<br />
Any sufficiently capable programming language is ''non-total'', which is to say you can write expressions that do not produce a value: common examples are an exception thrown, an infinite loop, or unproductive recursion, e.g. the following definition in Haskell:<br />
<br />
<haskell><br />
noreturn :: Integer -> Integer<br />
noreturn x = negate (noreturn x)<br />
</haskell><br />
<br />
or the following Python function:<br />
<br />
def noreturn(x):<br />
while True:<br />
x = -x<br />
<br />
return x # not reached<br />
<br />
both fail to produce a value when executed. We say that <tt>noreturn x</tt> is undefined, and write <tt>noreturn x = [[Bottom|⊥]]</tt>.<br />
<br />
In Python the following expression to check if <tt>2</tt> is in some list:<br />
<br />
2 in [2,4,noreturn(5)]<br />
<br />
also fails to have a value, because in order to construct the list, the interpreter tries to work out <tt>noreturn(5)</tt>, which of course doesn't return a value. This is called '''innermost-first''' evaluation: in order to call a function with some arguments, you first have to calculate what all the arguments are, starting from the innermost function call and working outwards. The result is that Python is strict, in the sense that calling any function with an undefined argument produces an undefined value, i.e. <tt>f(⊥) = ⊥</tt>. If your language uses innermost-first evaluation, it correspondingly must have strict semantics.<br />
<br />
In Haskell, an analogous expression:<br />
<br />
<haskell><br />
elem 2 [2, 4, noreturn 5]<br />
</haskell><br />
<br />
in fact has the value <tt>True</tt>. The program does not have to compute <tt>noreturn 5</tt> because it is irrelevant to the overall value of the computation: only the values that are necessary to the result need be computed. This is called '''outermost-first''' evaluation because you first look at the outermost function call, <tt>elem</tt>, to see if it needs to use its arguments, and only if it does do you look at what those arguments are. This means that you can write a function that doesn't look at its argument, so it will return a value even if the argument is <tt>⊥</tt>. Such functions are not strict, i.e. they satisfy <tt>f(⊥) ≠ ⊥</tt>. Practically, this means that Haskell functions need not completely compute their arguments before using them, which is why e.g. <tt>take 3 [1..]</tt> can produce <tt>[1,2,3]</tt> even though it is given a conceptually infinite list.<br />
<br />
Note that outermost-first evaluation is not the only way to have non-strict semantics: a speculative evaluation strategy, that evaluated arguments in parallel with the function in case they were needed later, could also be non-strict, as long as whenever the speculative evaluation failed, the evaluation of the function continued.<br />
<br />
Note also that in order for a function to be truly non-strict, it must return something without inspecting its argument ''at all''. You might think that doesn't sound like a very useful function, but remember that it might be e.g. a partial application: the function <tt>(||) True</tt>, or equivalently <tt>\x -> True || x</tt> does not need to inspect its argument, since <tt>True || x</tt> is always <tt>True</tt>. There are other examples, too: constructors like <tt>Just</tt> wrap their argument without inspecting it, and some other functions apply constructors ''before'' looking at the argument, and hence still produce a partial result, e.g. <tt>inits ⊥ = [] : ⊥</tt><br />
<br />
=== Why? ===<br />
<br />
The important thing to understand about non-strict semantics is that it is not a performance feature. Non-strict semantics allows your language to only evaluate the things it needs to, but if you write your programs carefully, you'll only compute what is absolutely necessary ''anyway'', so the extra time your program spends working out what should and shouldn't be evaluated is time wasted. For this reason, a very well-optimised strict program will frequently outperform even the fastest non-strict program.<br />
<br />
However, the real and major advantage that non-strictness gives you over strict languages is you get to write cleaner and more composable code. In particular, you can separate ''production'' and ''consumption'' of data: don't know how many prime numbers you're going to need? Just make `primes` a list of ''all'' prime numbers, and then which ones actually get ''generated'' depends on how you use them in the rest of your code. By contrast, writing code in a strict language that constructs a data structure in response to demand usually will require first-class functions and/or a lot of manual hoop-jumping to make it all behave itself.<br />
<br />
Consider the following Haskell function definition:<br />
<br />
<haskell><br />
any :: (a -> Bool) -> [a] -> Bool<br />
any p = or . map p<br />
</haskell><br />
<br />
Because <tt>or</tt> uses non-strictness to stop at the first <tt>True</tt> in the input, <tt>map</tt> doesn't even need to know that only the first half of the list might be needed. We can write <tt>map</tt> in the completely straightforward and obviously correct way, and still have it interact well with <tt>or</tt> in this way; <tt>map</tt> produces data, <tt>or</tt> consumes it, and the two are properly decoupled.<br />
<br />
In a strict langauge, you'd have to write the recursion out manually:<br />
<br />
<haskell><br />
any p [] = False<br />
any p (x:xs)<br />
| p x = True<br />
| otherwise = any p xs<br />
</haskell><br />
<br />
since in strict languages only builtin control structures can decide whether some bit of code gets executed or not, ordinary functions like <tt>or</tt> can't.<br />
<br />
It's this additional power that Haskell has that leads people to say you can define your own control structures as normal Haskell functions, which allows all sorts of interesting patterns to be abstracted in an incredibly lightweight fashion. Labelled for-loops are a ''library'' in Haskell, rather than requiring special syntax and language support.<br />
<br />
=== How do I stop it? ===<br />
<br />
As mentioned above, non-strictness can hurt performance, e.g. if a result is definitely going to be needed later, you might as well evaluate it now, to avoid having to hold on to all the data that goes into it. Fortunately, the Haskell designers were aware of these problems and introduced a loophole or two so that we could force our programs to be strict when necessary: see [[Performance/Strictness]] and [[seq]].</div>Benmachinehttps://wiki.haskell.org/User:Benmachine/Non-strict_semanticsUser:Benmachine/Non-strict semantics2013-09-14T16:58:07Z<p>Benmachine: </p>
<hr />
<div>An expression language is said to have '''non-strict semantics''' if expressions can have a value even if some of their subexpressions do not. Haskell is one of the few modern languages to have non-strict semantics by default: nearly every other language has [[strict semantics]], in which if any subexpression fails to have a value, the whole expression fails with it.<br />
<br />
=== What? ===<br />
<br />
Any sufficiently capable programming language is ''non-total'', which is to say you can write expressions that do not produce a value: common examples are an exception thrown, an infinite loop, or unproductive recursion, e.g. the following definition in Haskell:<br />
<br />
<haskell><br />
noreturn :: Integer -> Integer<br />
noreturn x = negate (noreturn x)<br />
</haskell><br />
<br />
or the following Python function:<br />
<br />
def noreturn(x):<br />
while True:<br />
x = -x<br />
<br />
return x # not reached<br />
<br />
both fail to produce a value when executed. We say that <tt>noreturn x</tt> is undefined, and write <tt>noreturn x = [[Bottom|⊥]]</tt>.<br />
<br />
In Python the following expression to check if <tt>2</tt> is in some list:<br />
<br />
2 in [2,4,noreturn(5)]<br />
<br />
also fails to have a value, because in order to construct the list, the interpreter tries to work out <tt>noreturn(5)</tt>, which of course doesn't return a value. This is called '''innermost-first''' evaluation: in order to call a function with some arguments, you first have to calculate what all the arguments are, starting from the innermost function call and working outwards. The result is that Python is strict, in the sense that calling any function with an undefined argument produces an undefined value, i.e. <tt>f(⊥) = ⊥</tt>. If your language uses innermost-first evaluation, it correspondingly must have strict semantics.<br />
<br />
In Haskell, an analogous expression:<br />
<br />
<haskell><br />
elem 2 [2, 4, noreturn 5]<br />
</haskell><br />
<br />
in fact has the value <tt>True</tt>. The program does not have to compute <tt>noreturn 5</tt> because it is irrelevant to the overall value of the computation: only the values that are necessary to the result need be computed. This is called '''outermost-first''' evaluation because you first look at the outermost function call, <tt>elem</tt>, to see if it needs to use its arguments, and only if it does do you look at what those arguments are. This means that you can write a function that doesn't look at its argument, so it will return a value even if the argument is <tt>⊥</tt>. Such functions are not strict, i.e. they satisfy <tt>f(⊥) ≠ ⊥</tt>. Practically, this means that Haskell functions need not completely compute their arguments before using them, which is why e.g. <tt>take 3 [1..]</tt> can produce <tt>[1,2,3]</tt> even though it is given a conceptually infinite list.<br />
<br />
Note that outermost-first evaluation is not the only way to have non-strict semantics: a speculative evaluation strategy, that evaluated arguments in parallel with the function in case they were needed later, could also be non-strict, as long as whenever the speculative evaluation failed, the evaluation of the function continued.<br />
<br />
Note also that in order for a function to be truly non-strict, it must return something without inspecting its argument ''at all''. You might think that doesn't sound like a very useful function, but remember that it might be e.g. a partial application: the function <tt>(||) True</tt>, or equivalently <tt>\x -> True || x</tt> does not need to inspect its argument, since <tt>True || x</tt> is always <tt>True</tt>. There are other examples, too: constructors like <tt>Just</tt> wrap their argument without inspecting it, and some other functions apply constructors ''before'' looking at the argument, and hence still produce a partial result, e.g. <tt>inits ⊥ = [] : ⊥</tt><br />
<br />
=== Why? ===<br />
<br />
The important thing to understand about non-strict semantics is that it is not a performance feature. Non-strict semantics allows your language to only evaluate the things it needs to, but if you write your programs carefully, you'll only compute what is absolutely necessary ''anyway'', so the extra time your program spends working out what should and shouldn't be evaluated is time wasted. For this reason, a very well-optimised strict program will frequently outperform even the fastest non-strict program.<br />
<br />
However, the real and major advantage that non-strictness gives you over strict languages is you get to write cleaner and more composable code. In particular, you can separate ''production'' and ''consumption'' of data: don't know how many prime numbers you're going to need? Just make `primes` a list of ''all'' prime numbers, and then which ones actually get ''generated'' depends on how you use them in the rest of your code. By contrast, writing code in a strict language that constructs a data structure in response to demand usually will require first-class functions and/or a lot of manual hoop-jumping to make it all behave itself.<br />
<br />
Consider the following Haskell function definition:<br />
<br />
<haskell><br />
any :: (a -> Bool) -> [a] -> Bool<br />
any p = or . map p<br />
</haskell><br />
<br />
Because <tt>or</tt> uses non-strictness to stop at the first <tt>True</tt> in the input, <tt>map</tt> doesn't even need to know that only the first half of the list might be needed. We can write <tt>map</tt> in the completely straightforward and obviously correct way, and still have it interact well with <tt>or</tt> in this way; <tt>map</tt> produces data, <tt>or</tt> consumes it, and the two are properly decoupled.<br />
<br />
In a strict langauge, you'd have to write the recursion out manually:<br />
<br />
<haskell><br />
any p [] = False<br />
any p (x:xs)<br />
| p x = True<br />
| otherwise = any p xs<br />
</haskell><br />
<br />
since in strict languages only builtin control structures can decide whether some bit of code gets executed or not, ordinary functions like <tt>or</tt> can't.<br />
<br />
It's this additional power that Haskell has that leads people to say you can define your own control structures as normal Haskell functions, which allows all sorts of interesting patterns to be abstracted in an incredibly lightweight fashion. Labelled for-loops are a ''library'' in Haskell, rather than requiring special syntax and language support.<br />
<br />
=== How do I stop it? ===<br />
<br />
As mentioned above, non-strictness can hurt performance, e.g. if a result is definitely going to be needed later, you might as well evaluate it now, to avoid having to hold on to all the data that goes into it. Fortunately, the Haskell designers were aware of these problems and introduced a loophole or two so that we could force our programs to be strict when necessary: see [[Performance/Strictness]] and [[seq]].</div>Benmachinehttps://wiki.haskell.org/User:Benmachine/Non-strict_semanticsUser:Benmachine/Non-strict semantics2013-04-08T11:11:01Z<p>Benmachine: /* Why? */</p>
<hr />
<div>An expression language is said to have '''non-strict semantics''' if expressions can have a value even if some of their subexpressions do not. Haskell is one of the few modern languages to have non-strict semantics by default: nearly every other language has [[strict semantics]], in which if any subexpression fails to have a value, the whole expression fails with it.<br />
<br />
=== What? ===<br />
<br />
Any sufficiently capable programming language is ''non-total'', which is to say you can write expressions that do not produce a value: common examples are an exception thrown, an infinite loop, or unproductive recursion, e.g. the following definition in Haskell:<br />
<br />
<haskell><br />
noreturn :: Integer -> Integer<br />
noreturn x = negate (noreturn x)<br />
</haskell><br />
<br />
or the following Python function:<br />
<br />
def noreturn(x):<br />
while True:<br />
x = -x<br />
<br />
return x # not reached<br />
<br />
both fail to produce a value when executed. We say that <tt>noreturn x</tt> is undefined, and write <tt>noreturn x = [[Bottom|⊥]]</tt>.<br />
<br />
In Python the following expression to check if <tt>2</tt> is in some list:<br />
<br />
2 in [2,4,noreturn(5)]<br />
<br />
also fails to have a value, because in order to construct the list, the interpreter tries to work out <tt>noreturn(5)</tt>, which of course doesn't return a value. This is called '''innermost-first''' evaluation: in order to call a function with some arguments, you first have to calculate what all the arguments are, starting from the innermost function call and working outwards. The result is that Python is strict, in the sense that calling any function with an undefined argument produces an undefined value, i.e. <tt>f(⊥) = ⊥</tt>. If your language uses innermost-first evaluation, it correspondingly must have strict semantics.<br />
<br />
In Haskell, an analogous expression:<br />
<br />
<haskell><br />
elem 2 [2, 4, noreturn 5]<br />
</haskell><br />
<br />
in fact has the value <tt>True</tt>. The program does not try to compute <tt>noreturn 5</tt> because it is irrelevant to the overall value of the computation: only the values that are necessary to the result are computed. This is called '''outermost-first''' evaluation because you first look at the outermost function call, <tt>elem</tt>, to see if it needs to use its arguments, and only if it does do you look at what those arguments are. This means that you can write a function that doesn't look at its argument, so it will return a value even if the argument is <tt>⊥</tt>. Such functions are not strict, i.e. they satisfy <tt>f(⊥) ≠ ⊥</tt>. Practically, this means that Haskell functions need not completely compute their arguments before using them, which is why e.g. <tt>take 3 [1..]</tt> can produce <tt>[1,2,3]</tt> even though it is given a conceptually infinite list.<br />
<br />
Note that outermost-first evaluation is not the only way to have non-strict semantics: a speculative evaluation strategy, that evaluated arguments in parallel with the function in case they were needed later, could also be non-strict, as long as whenever the speculative evaluation failed, the evaluation of the function continued.<br />
<br />
Note also that in order for a function to be truly non-strict, it must return a result without inspecting its argument ''at all''. You might think that doesn't sound like a very useful function, but remember that it might be e.g. a partial application: the function <tt>(||) True</tt>, or equivalently <tt>\x -> True || x</tt> does not need to inspect its argument, since <tt>True || x</tt> is always <tt>True</tt>. There are other examples, too: constructors like <tt>Just</tt> wrap their argument without inspecting it, and some other functions apply constructors ''before'' looking at the argument, and hence still produce a partial result, e.g. <tt>inits ⊥ = [] : ⊥</tt><br />
<br />
=== Why? ===<br />
<br />
The important thing to understand about non-strict semantics is that it is not a performance feature. Non-strict semantics allows your language to only evaluate the things it needs to, but if you write your programs carefully, you'll only compute what is absolutely necessary ''anyway'', so the extra time your program spends working out what should and shouldn't be evaluated is time wasted. For this reason, a very well-optimised strict program will frequently outperform even the fastest non-strict program.<br />
<br />
However, the real and major advantage that non-strictness gives you over strict languages is you get to write cleaner and more composable code. In particular, you can separate ''production'' and ''consumption'' of data: don't know how many prime numbers you're going to need? Just make `primes` a list of ''all'' prime numbers, and then which ones actually get ''generated'' depends on how you use them in the rest of your code. By contrast, writing code in a strict language that constructs a data structure in response to demand usually will require first-class functions and/or a lot of manual hoop-jumping to make it all behave itself.<br />
<br />
Consider the following Haskell function definition:<br />
<br />
<haskell><br />
any :: (a -> Bool) -> [a] -> Bool<br />
any p = or . map p<br />
</haskell><br />
<br />
Because <tt>or</tt> uses non-strictness to stop at the first <tt>True</tt> in the input, <tt>map</tt> doesn't even need to know that only the first half of the list might be needed. We can write <tt>map</tt> in the completely straightforward and obviously correct way, and still have it interact well with <tt>or</tt> in this way; <tt>map</tt> produces data, <tt>or</tt> consumes it, and the two are properly decoupled.<br />
<br />
In a strict langauge, you'd have to write the recursion out manually:<br />
<br />
<haskell><br />
any p [] = False<br />
any p (x:xs)<br />
| p x = True<br />
| otherwise = any p xs<br />
</haskell><br />
<br />
since in strict languages only builtin control structures can decide whether some bit of code gets executed or not, ordinary functions like <tt>or</tt> can't.<br />
<br />
It's this additional power that Haskell has that leads people to say you can define your own control structures as normal Haskell functions, which allows all sorts of interesting patterns to be abstracted in an incredibly lightweight fashion. Labelled for-loops are a ''library'' in Haskell, rather than requiring special syntax and language support.<br />
<br />
=== How do I stop it? ===<br />
<br />
As mentioned above, non-strictness can hurt performance: if a result is definitely going to be needed later, you might as well evaluate it now, to avoid having to hold on to all the data that goes into it. Fortunately, the Haskell designers were aware of these problems and introduced a loophole or two so that we could force our programs to be strict when necessary: see [[Performance/Strictness]] and [[seq]].</div>Benmachinehttps://wiki.haskell.org/Impredicative_typesImpredicative types2013-01-21T16:24:43Z<p>Benmachine: </p>
<hr />
<div>Impredicative types are an advanced form of polymorphism, to be contrasted with [[rank-N types]]. <br />
<br />
Standard Haskell allows polymorphic types via the use of type variables, which are understood to be ''universally quantified'': <tt>id :: a -> a</tt> means "''for all'' types <tt>a</tt>, <tt>id</tt> can take an argument and return a result of that type". All universal quantifiers ("for all"s) must appear at the beginning of a type.<br />
<br />
Higher-rank polymorphism (e.g. [[rank-N types]]) allows universal quantifiers to appear inside function types as well. It turns out that appearing to the right of function arrows is not interesting: <tt>Int -> forall a. a -> [a]</tt> is actually the same as <tt>forall a. Int -> a -> [a]</tt>. However, higher-rank polymorphism allows quantifiers to the ''left'' of function arrows, too, and <tt>(forall a. [a] -> Int) -> Int</tt> really ''is'' different from <tt>forall a. ([a] -> Int) -> Int</tt>.<br />
<br />
Impredicative types take this idea to its natural conclusion: universal quantifiers are allowed ''anywhere'' in a type, even inside normal datatypes like lists or <tt>Maybe</tt>. The GHC User's Guide gives the following example:<br />
<br />
<haskell><br />
f :: Maybe (forall a. [a] -> [a]) -> Maybe ([Int], [Char])<br />
f (Just g) = Just (g [3], g "hello")<br />
f Nothing = Nothing<br />
</haskell><br />
<br />
However, impredicative types do not mix very well with Haskell's type inference, so to actually use the above function with GHC 7.6.1 you need to specify the full (unpleasant) type signature for the <tt>Just</tt> constructor:<br />
<br />
<haskell><br />
ghci> f ((Just :: (forall a. [a] -> [a]) -> Maybe (forall a. [a] -> [a])) reverse)<br />
Just ([3],"olleh")<br />
</haskell><br />
<br />
Other examples are more successful: see below.<br />
<br />
=== See also ===<br />
<br />
* [http://www.haskell.org/ghc/docs/latest/html/users_guide/other-type-extensions.html#impredicative-polymorphism The GHC User's Guide on impredicative polymorphism].<br />
* [http://augustss.blogspot.co.uk/2011/07/impredicative-polymorphism-use-case-in.html A Pythonesque EDSL that makes use of impredicative polymorphism]<br />
* [http://stackoverflow.com/a/14065493/812053 A writeup of where ImpredicativePolymorphism is used in a GHC plugin to store a lookup table of strings to polymorphic functions]<br />
<br />
[[Category:Glossary]]</div>Benmachinehttps://wiki.haskell.org/Impredicative_typesImpredicative types2013-01-04T16:43:18Z<p>Benmachine: Rewrite most of the article</p>
<hr />
<div>Impredicative types are an advanced form of polymorphism, to be contrasted with [[rank-N types]]. <br />
<br />
Standard Haskell allows polymorphic types via the use of type variables, which are understood to be ''universally quantified'': <tt>id :: a -> a</tt> means "''for all'' types <tt>a</tt>, <tt>id</tt> can take an argument and return a result of that type". All universal quantifiers ("for all"s) must appear at the beginning of a type.<br />
<br />
Higher-rank polymorphism (e.g. [[rank-N types]]) allows universal quantifiers to appear inside function types as well. It turns out that appearing to the right of function arrows is not interesting: <tt>Int -> forall a. a -> [a]</tt> is actually the same as <tt>forall a. Int -> a -> [a]</tt>. However, higher-rank polymorphism allows quantifiers to the ''left'' of function arrows, too, and <tt>(forall a. [a] -> Int) -> Int</tt> really ''is'' different from <tt>forall a. ([a] -> Int) -> Int</tt>.<br />
<br />
Impredicative types take this idea to its natural conclusion: universal quantifiers are allowed ''anywhere'' in a type, even inside normal datatypes like lists or <tt>Maybe</tt>. The GHC User's Guide gives the following example:<br />
<br />
<haskell><br />
f :: Maybe (forall a. [a] -> [a]) -> Maybe ([Int], [Char])<br />
f (Just g) = Just (g [3], g "hello")<br />
f Nothing = Nothing<br />
</haskell><br />
<br />
However, impredicative types do not mix very well with Haskell's type inference, so to actually use the above function with latest GHC you need to specify the full (unpleasant) type signature for the <tt>Just</tt> constructor:<br />
<br />
<haskell><br />
ghci> f ((Just :: (forall a. [a] -> [a]) -> Maybe (forall a. [a] -> [a])) reverse)<br />
Just ([3],"olleh")<br />
</haskell><br />
<br />
Other examples are more successful: see below.<br />
<br />
=== See also ===<br />
<br />
* [http://www.haskell.org/ghc/docs/latest/html/users_guide/other-type-extensions.html#impredicative-polymorphism The GHC User's Guide on impredicative polymorphism].<br />
* [http://augustss.blogspot.co.uk/2011/07/impredicative-polymorphism-use-case-in.html A Pythonesque EDSL that makes use of impredicative polymorphism]<br />
* [http://stackoverflow.com/a/14065493/812053 A writeup of where ImpredicativePolymorphism is used in a GHC plugin to store a lookup table of strings to polymorphic functions]<br />
<br />
[[Category:Glossary]]</div>Benmachinehttps://wiki.haskell.org/Impredicative_typesImpredicative types2012-12-29T23:19:05Z<p>Benmachine: /* See also */</p>
<hr />
<div>Impredicative types are an advanced form of polymorphism, to be contrasted with [[rank-N types]].<br />
<br />
A standard Haskell type is universally quantified by default, and quantifiers can only appear at the top level of a type or to the right of function arrows.<br />
<br />
A higher-rank polymorphic type allows universal quantifiers to appear to the left of function arrows as well, so that function arguments can be functions that are themselves polymorphic.<br />
<br />
An impredicative type, on the other hand, allows universal quantifiers anywhere: in particular, may contain ordinary datatypes with polymorphic components. The GHC User's Guide gives the following example:<br />
<br />
<haskell><br />
f :: Maybe (forall a. [a] -> [a]) -> Maybe ([Int], [Char])<br />
f (Just g) = Just (g [3], g "hello")<br />
f Nothing = Nothing<br />
</haskell><br />
<br />
Impredicative types are enabled in GHC with the <hask>{-# LANGUAGE ImpredicativeTypes #-}</hask> pragma. They are among the less well-used and well-tested language extensions, and so some caution is advised in their use. <br />
<br />
=== See also ===<br />
<br />
* [http://www.haskell.org/ghc/docs/latest/html/users_guide/other-type-extensions.html#impredicative-polymorphism The GHC User's Guide on impredicative polymorphism].<br />
* [http://augustss.blogspot.co.uk/2011/07/impredicative-polymorphism-use-case-in.html A Pythonesque EDSL that makes use of impredicative polymorphism]<br />
* [http://stackoverflow.com/a/14065493/812053 A writeup of where ImpredicativePolymorphism is used in a GHC plugin to store a lookup table of strings to polymorphic functions]<br />
<br />
[[Category:Glossary]]</div>Benmachinehttps://wiki.haskell.org/SeqSeq2012-12-27T03:09:17Z<p>Benmachine: </p>
<hr />
<div><span>{{DISPLAYTITLE:seq}}</span><br />
<br />
The <tt>seq</tt> function is the most basic method of introducing strictness to a Haskell program. <tt>seq :: a -> b -> b</tt> takes two arguments of any type, and returns the second. However, it also has the important property that it is magically strict in its first argument. In essence, <tt>seq</tt> is defined by the following two equations:<br />
<br />
<haskell><br />
⊥ `seq` b = ⊥<br />
a `seq` b = b<br />
</haskell><br />
<br />
See [[Bottom]] for an explanation of the ⊥ symbol.<br />
<br />
A common misconception regarding <tt>seq</tt> is that <tt>seq x</tt> "evaluates" <tt>x</tt>. Well, sort of. <tt>seq</tt> doesn't evaluate anything just by virtue of existing in the source file, all it does is introduce an artificial data dependency of one value on another: when the result of <tt>seq</tt> is evaluated, the first argument must also (sort of; see below) be evaluated. As an example, suppose <tt>x :: Integer</tt>, then <tt>seq x b</tt> behaves essentially like <tt>if x == 0 then b else b</tt> – unconditionally equal to <tt>b</tt>, but forcing <tt>x</tt> along the way. In particular, the expression <tt>x `seq` x</tt> is completely redundant, and always has exactly the same effect as just writing <tt>x</tt>.<br />
<br />
Strictly speaking, the two equations of <tt>seq</tt> are all it must satisfy, and if the compiler can statically prove that the first argument is not ⊥, or that its second argument ''is'', it doesn't have to evaluate anything to meet its obligations. In practice, this almost never happens, and would probably be considered highly counterintuitive behaviour on the part of GHC (or whatever else you use to run your code). However, it ''is'' the case that evaluating <tt>b</tt> and ''then'' <tt>a</tt>, then returning <tt>b</tt> is a perfectly legitimate thing to do; it is to prevent this ambiguity that <tt>pseq</tt> was invented, but that's another story.<br />
<br />
=== Common uses of <tt>seq</tt> ===<br />
<br />
<tt>seq</tt> is typically used in the semantic interpretation of other strictness techniques, like strictness annotations in data types, or GHC's <tt>BangPatterns</tt> extension. For example, the meaning of this:<br />
<br />
<haskell><br />
f !x !y = z<br />
</haskell><br />
<br />
is this:<br />
<br />
<haskell><br />
f x y | x `seq` y `seq` False = undefined<br />
| otherwise = z<br />
</haskell><br />
<br />
although that literal translation may not actually take place.<br />
<br />
<tt>seq</tt> is frequently used with accumulating parameters to ensure that they don't become huge thunks, which will be forced at the end anyway. For example, strict foldl:<br />
<br />
<haskell><br />
foldl' :: (a -> b -> a) -> a -> [b] -> a<br />
foldl' _ z [] = z<br />
foldl' f z (x:xs) = let z' = f z x in z' `seq` foldl' f z' xs<br />
</haskell><br />
<br />
It's also used to define strict application:<br />
<br />
<haskell><br />
($!) :: (a -> b) -> a -> b<br />
f $! x = x `seq` f x<br />
</haskell><br />
<br />
which is useful for some of the same reasons.<br />
<br />
=== Controversy! ===<br />
<br />
Note that <tt>seq</tt> is the ''only'' way to force evaluation of a value with a function type (except by applying it, which is liable to cause other problems). As such, it is the only reason why Haskell programs are able to distinguish between the following two values:<br />
<br />
<haskell><br />
undefined :: a -> b<br />
const undefined :: a -> b<br />
</haskell><br />
<br />
This violates the principle from lambda calculus of extensionality of functions, or eta-conversion, because <tt>f</tt> and <tt>\x -> f x</tt> are distinct functions, even though they return the same output for ''every'' input. For this reason, <tt>seq</tt>, and this distinction, is sometimes ignored e.g. when assessing the correctness of [[Correctness of short cut fusion|optimisation techniques]] or type class instances.<br />
<br />
== See also ==<br />
<br />
* [http://stackoverflow.com/questions/12687392/why-is-seq-bad Why is seq bad?]<br />
<br />
[[Category:Glossary]]</div>Benmachinehttps://wiki.haskell.org/SeqSeq2012-12-27T02:54:19Z<p>Benmachine: unnecessary whitespace</p>
<hr />
<div><span>{{DISPLAYTITLE:seq}}</span><br />
<br />
The <tt>seq</tt> function is the most basic method of introducing strictness to a Haskell program. <tt>seq :: a -> b -> b</tt> takes two arguments of any type, and returns the second. However, it also has the important property that it is magically strict in its first argument. In essence, <tt>seq</tt> is defined by the following two equations:<br />
<br />
<haskell><br />
⊥ `seq` b = ⊥<br />
a `seq` b = b<br />
</haskell><br />
<br />
See [[Bottom]] for an explanation of the ⊥ symbol.<br />
<br />
A common misconception regarding <tt>seq</tt> is that <tt>seq x</tt> "evaluates" <tt>x</tt>. Well, sort of. <tt>seq</tt> doesn't evaluate anything just by virtue of existing in the source file, all it does is introduce an artificial data dependency of one value on another: when the result of <tt>seq</tt> is evaluated, the first argument must also be evaluated. As an example, suppose <tt>x :: Integer</tt>, then <tt>seq x b</tt> behaves essentially like <tt>if x == 0 then b else b</tt> – unconditionally equal to <tt>b</tt>, but forcing <tt>x</tt> along the way. In particular, the expression <tt>x `seq` x</tt> is completely redundant, and always has exactly the same effect as just writing <tt>x</tt>.<br />
<br />
Strictly speaking, the two equations of <tt>seq</tt> are all it must satisfy, and if the compiler can statically prove that the first argument is not ⊥, it doesn't have to evaluate it to meet its obligations. In practice, this almost never happens, and would probably be considered highly counterintuitive behaviour on the part of GHC (or whatever else you use to run your code). However, it ''is'' the case that evaluating <tt>b</tt> and ''then'' <tt>a</tt>, then returning <tt>b</tt> is a perfectly legitimate thing to do; it is to prevent this ambiguity that <tt>pseq</tt> was invented, but that's another story.<br />
<br />
=== Common uses of <tt>seq</tt> ===<br />
<br />
<tt>seq</tt> is typically used in the semantic interpretation of other strictness techniques, like strictness annotations in data types, or GHC's <tt>BangPatterns</tt> extension. For example, the meaning of this:<br />
<br />
<haskell><br />
f !x !y = z<br />
</haskell><br />
<br />
is this:<br />
<br />
<haskell><br />
f x y | x `seq` y `seq` False = undefined<br />
| otherwise = z<br />
</haskell><br />
<br />
although that literal translation may not actually take place.<br />
<br />
<tt>seq</tt> is frequently used with accumulating parameters to ensure that they don't become huge thunks, which will be forced at the end anyway. For example, strict foldl:<br />
<br />
<haskell><br />
foldl' :: (a -> b -> a) -> a -> [b] -> a<br />
foldl' _ z [] = z<br />
foldl' f z (x:xs) = let z' = f z x in z' `seq` foldl' f z' xs<br />
</haskell><br />
<br />
It's also used to define strict application:<br />
<br />
<haskell><br />
($!) :: (a -> b) -> a -> b<br />
f $! x = x `seq` f x<br />
</haskell><br />
<br />
which is useful for some of the same reasons.<br />
<br />
=== Controversy! ===<br />
<br />
Note that <tt>seq</tt> is the ''only'' way to force evaluation of a value with a function type (except by applying it, which is liable to cause other problems). As such, it is the only reason why Haskell programs are able to distinguish between the following two values:<br />
<br />
<haskell><br />
undefined :: a -> b<br />
const undefined :: a -> b<br />
</haskell><br />
<br />
This violates the principle from lambda calculus of extensionality of functions, or eta-conversion, because <tt>f</tt> and <tt>\x -> f x</tt> are distinct functions, even though they return the same output for ''every'' input. For this reason, <tt>seq</tt>, and this distinction, is sometimes ignored e.g. when assessing the correctness of [[Correctness of short cut fusion|optimisation techniques]] or type class instances.<br />
<br />
== See also ==<br />
<br />
* [http://stackoverflow.com/questions/12687392/why-is-seq-bad Why is seq bad?]<br />
<br />
[[Category:Glossary]]</div>Benmachinehttps://wiki.haskell.org/Talk:Functional_dependenciesTalk:Functional dependencies2012-12-27T02:48:15Z<p>Benmachine: Talk:Functional dependency moved to Talk:Functional dependencies: More often referred to in plural (e.g. extension name)</p>
<hr />
<div>This page was moved from [[Functional dependencies]], but I think it's more natural there - the extension is in the plural and they are usually referred to in plural. I think it should be moved back.</div>Benmachinehttps://wiki.haskell.org/Talk:Functional_dependencyTalk:Functional dependency2012-12-27T02:48:15Z<p>Benmachine: Talk:Functional dependency moved to Talk:Functional dependencies: More often referred to in plural (e.g. extension name)</p>
<hr />
<div>#REDIRECT [[Talk:Functional dependencies]]</div>Benmachinehttps://wiki.haskell.org/Functional_dependenciesFunctional dependencies2012-12-27T02:48:13Z<p>Benmachine: Functional dependency moved to Functional dependencies over redirect: More often referred to in plural (e.g. extension name)</p>
<hr />
<div>[[Category:Glossary]]<br />
[[Category:Language extensions]]<br />
Functional dependencies are used to constrain the parameters of type classes. They let you state that in a [[multi-parameter type class]], one of the [[parameter]]s can be determined from the others, so that the [[parameter]] determined by the others can, for example, be the return type but none of the argument types of some of the methods.<br />
<br />
==Examples==<br />
Suppose you want to implement some code to perform simple [[linear algebra]]:<br />
<haskell><br />
data Vector = Vector Int Int deriving (Eq, Show)<br />
data Matrix = Matrix Vector Vector deriving (Eq, Show)<br />
</haskell><br />
You want these to behave as much like numbers as possible. So you might start by overloading Haskell's Num class:<br />
<haskell><br />
instance Num Vector where<br />
Vector a1 b1 + Vector a2 b2 = Vector (a1+a2) (b1+b2)<br />
Vector a1 b1 - Vector a2 b2 = Vector (a1-a2) (b1-b2)<br />
{- ... and so on ... -}<br />
<br />
instance Num Matrix where<br />
Matrix a1 b1 + Matrix a2 b2 = Matrix (a1+a2) (b1+b2)<br />
Matrix a1 b1 - Matrix a2 b2 = Matrix (a1-a2) (b1-b2)<br />
{- ... and so on ... -}<br />
</haskell><br />
The problem comes when you want to start multiplying quantities. You really need a multiplication function which overloads to different types:<br />
<haskell><br />
(*) :: Matrix -> Matrix -> Matrix<br />
(*) :: Matrix -> Vector -> Vector<br />
(*) :: Matrix -> Int -> Matrix<br />
(*) :: Int -> Matrix -> Matrix<br />
{- ... and so on ... -}<br />
</haskell><br />
How do we specify a type class which allows all these possibilities?<br />
<br />
We could try this:<br />
<haskell><br />
class Mult a b c where<br />
(*) :: a -> b -> c<br />
<br />
instance Mult Matrix Matrix Matrix where<br />
{- ... -}<br />
<br />
instance Mult Matrix Vector Vector where<br />
{- ... -}<br />
</haskell><br />
That, however, isn't really what we want. As it stands, even a simple expression like this has an ambiguous type unless you supply an additional type declaration on the intermediate expression:<br />
<haskell><br />
m1, m2, m3 :: Matrix<br />
(m1 * m2) * m3 -- type error; type of (m1*m2) is ambiguous<br />
(m1 * m2) :: Matrix * m3 -- this is ok<br />
</haskell><br />
After all, nothing is stopping someone from coming along later and adding another instance:<br />
<haskell><br />
instance Mult Matrix Matrix (Maybe Char) where<br />
{- whatever -}<br />
</haskell><br />
The problem is that <hask>c</hask> shouldn't really be a free type variable. When you know the types of the things that you're multiplying, the result type should be determined from that information alone.<br />
<br />
You can express this by specifying a functional dependency, or fundep for short:<br />
<haskell><br />
class Mult a b c | a b -> c where<br />
(*) :: a -> b -> c<br />
</haskell><br />
This tells Haskell that <hask>c</hask> is uniquely determined from <hask>a</hask> and <hask>b</hask>.<br />
<br />
Fundeps have lots more uses than just implementing C++-style function overloading, of course. See [http://web.cecs.pdx.edu/~mpj/pubs/fundeps.html the paper] by Mark P. Jones for further details.<br />
<br />
Fundeps are not standard Haskell 98. (Nor are [[multi-parameter type class]]es, for that matter.) They are, however, supported at least in [[GHC]] and [[Hugs]] and will almost certainly end up in Haskell'.<br />
<br />
[[User:AndrewBromage]]<br />
<br />
== Another example ==<br />
<br />
The following example makes use of the FlexibleInstances, MultiParamTypeClasses and FunctionalDependencies GHC extensions.<br />
<br />
<haskell><br />
-- Read as: "container" type determines "elem" type.<br />
class Extract container elem | container -> elem where<br />
extract :: container -> elem<br />
</haskell><br />
<br />
The functional dependency "container -> elem" promises that we won't declare multiple instances with the same "container" type.<br />
<br />
<haskell><br />
instance Extract (a,b) a where<br />
extract (x,_) = x<br />
</haskell><br />
<br />
Because of the functional dependency we can't have the previous instance *and* this one:<br />
<br />
<haskell>-- instance Extract (a,b) b where ...</haskell><br />
<br />
Because of the functional dependency we can say:<br />
<br />
<haskell>v = extract ('x', 3)</haskell><br />
<br />
and it will infer the type <haskell>v :: Char</haskell><br />
<br />
Without the functional dependency, both instances above would be allowed, and the type of v would be potentially ambiguous. Even if only one instance is defined, the type system will not figure it out without the functional dependency.<br />
<br />
== Tutorials ==<br />
<br />
* [http://www.cs.chalmers.se/~hallgren/Papers/wm01.html Fun with functional dependencies], Thomas Hallgren (2001)<br />
* [[User:ConradParker/InstantInsanity | Type-Level Instant Insanity]], Conrad Parker (2007)<br />
<br />
== See also ==<br />
* [http://www.haskell.org/ghc/docs/latest/html/users_guide/type-class-extensions.html#functional-dependencies GHC documentation]</div>Benmachinehttps://wiki.haskell.org/Functional_dependencyFunctional dependency2012-12-27T02:48:13Z<p>Benmachine: Functional dependency moved to Functional dependencies over redirect: More often referred to in plural (e.g. extension name)</p>
<hr />
<div>#REDIRECT [[Functional dependencies]]</div>Benmachinehttps://wiki.haskell.org/Impredicative_typesImpredicative types2012-12-27T02:35:06Z<p>Benmachine: /* See also */</p>
<hr />
<div>Impredicative types are an advanced form of polymorphism, to be contrasted with [[rank-N types]].<br />
<br />
A standard Haskell type is universally quantified by default, and quantifiers can only appear at the top level of a type or to the right of function arrows.<br />
<br />
A higher-rank polymorphic type allows universal quantifiers to appear to the left of function arrows as well, so that function arguments can be functions that are themselves polymorphic.<br />
<br />
An impredicative type, on the other hand, allows universal quantifiers anywhere: in particular, may contain ordinary datatypes with polymorphic components. The GHC User's Guide gives the following example:<br />
<br />
<haskell><br />
f :: Maybe (forall a. [a] -> [a]) -> Maybe ([Int], [Char])<br />
f (Just g) = Just (g [3], g "hello")<br />
f Nothing = Nothing<br />
</haskell><br />
<br />
Impredicative types are enabled in GHC with the <hask>{-# LANGUAGE ImpredicativeTypes #-}</hask> pragma. They are among the less well-used and well-tested language extensions, and so some caution is advised in their use. <br />
<br />
=== See also ===<br />
<br />
* [http://www.haskell.org/ghc/docs/latest/html/users_guide/other-type-extensions.html#impredicative-polymorphism The GHC User's Guide on impredicative polymorphism].<br />
* [http://augustss.blogspot.co.uk/2011/07/impredicative-polymorphism-use-case-in.html A Pythonesque EDSL that makes use of impredicative polymorphism]<br />
<br />
[[Category:Glossary]]</div>Benmachinehttps://wiki.haskell.org/User:Benmachine/Overqualified_modulesUser:Benmachine/Overqualified modules2012-12-26T11:45:55Z<p>Benmachine: </p>
<hr />
<div>== Overqualified modules ==<br />
<br />
The hierarchical module system was originally proposed as an extension to the Haskell98 standard, and adopted formally in Haskell2010. It is typically regarded as one of the less controversial extensions, because more or less everyone agreed that single-token module names were liable to become a huge tangled mess with everyone stepping on each others' toes.<br />
<br />
=== Data.Data.Data ===<br />
<br />
I lack a little historical context here, since the extension was widespread before I was introduced to Haskell, but I think that the current layout of the module hierarchy is unsatisfactory. Having been given hierarchical modules, Haskellers seem to feel obliged to use them: single-component names are virtually unheard of. Yet in many cases, the additional categorisation seems to add no semantic content whatsoever. What do we learn about a module by its name <tt>Data.Bool</tt> that was not already evident in the <tt>Bool</tt>? Why is the <tt>Functor</tt> type class a piece of <tt>Data</tt> but the closely-related <tt>Applicative</tt> type class a <tt>Control</tt> structure? Why do we have <tt>Data.Monoid</tt> but <tt>Control.Category</tt>?<br />
<br />
=== Redundant specification ===<br />
<br />
There are certainly cases where the additional qualification adds meaning. Writing <hask>import Haskell</hask> at the top of your file seems meaningless, where in <hask>import Haskell.Parser</hask> you have a slightly better idea of what is being requested. However, minimalism is desirable: when adding a component to your module name, ask yourself if it resolves any confusion or prevents any ambiguity. I would argue that in <tt>Codec.Binary.UTF8.Generic</tt>, for example, nearly all of the name is redundant. There is no UTF-8 that is not a binary codec, and arguably the <tt>Generic</tt> component of the name is equally unenlightening. Just name the module <tt>UTF8</tt>, the shortest unambiguous description of its purpose.<br />
<br />
=== Redundant disambiguation ===<br />
<br />
One could argue that keeping module names long reduces the risk of collision. It's true that specifying more information in the module name might reduce the chance of some other module clashing with it, but often people confuse “information content” with “textual length”: clearly, grouping all monad-related modules under <tt>Control.Monad</tt> instead of just <tt>Monad</tt> is not going to stop two implementations of <tt>Reader</tt> from interfering with each other. So keep just the meaningful component of the name: what, after all, could possibly be named <tt>Monad</tt> except for a module housing the <tt>Monad</tt> class and related utility functions? Likewise <tt>Applicative</tt>, <tt>List</tt>, <tt>Exception</tt>, <tt>IO</tt>: all sorts of concepts are clearly going to exist only once in Haskell. Those that don't are no better served being <tt>Control.Monad.Reader</tt> than <tt>Monad.Reader</tt>.<br />
<br />
If you really want to avoid name collisions, take a leaf from syb's book: previously under the hierarchy <tt>Data.Generics</tt>, which not only suffered from <tt>Data</tt>-itis but also adequately described any generic programming mechanism, syb is starting to move over to the new, more specific <tt>Generics.SYB</tt> hierarchy. This drops the useless <tt>Data</tt> prefix and instead uses a component – the name of the package – that is very likely to be unique to this particular design and implementation. We appear to lose some "generality", but in reality the knowledge that you were using SYB in particular was probably already encoded in your program, since other generics libraries will have made different design decisions. The new name also emphasises the position of syb as a generics library, not the generics library – on an equal footing with Uniplate and other similar tools.<br />
<br />
=== Internal package politics ===<br />
<br />
Hierarchical modules do make internal structuring of a project easier; one only needs to look at something like Haskore's module list to see that they could clearly not just all be dumped in a single source directory. So that is a legitimate use, but of course there's not necessarily any reason why the internal structure of your project has to be reflected in the external API you provide. If you want twenty helper modules in various tidy subdirectories, fine, but you can probably re-export everything relevant (and it is good design not to export too much) in just a few root modules at the base of your hierarchy. Don't confuse what makes life easy for the library author with what makes things easy for the library user – and don't assume you need to trade one off against the other.<br />
<br />
=== Some syntactical digressions ===<br />
<br />
In addition to the above practical concerns, I also somewhat object to the overuse of the poor little <hask>.</hask> character. For example, one should in principle be able to write a list of all weekdays as <hask>[Monday..]</hask>, but this actually parses as a qualified reference to the Monday module – you'll need to use the marginally uglier <hask>[Monday ..]</hask>. This also demonstrates how the syntax for qualified operators is just plain ugly. It's hard to write and equally hard to read <hask>7 Prelude.+ 8</hask> or, to really rub it in, <hask>f Control.Category.. g</hask>.<br />
<br />
== Conclusion ==<br />
<br />
Hierarchical modules added some much-needed structure to Haskell's module namespace, but should be used sparingly and responsibly to avoid tragic keyboard wear every time I want to <hask>import qualified Text.ParserCombinators.Parsec.Combinator as PCPC</hask>. The policy on how best to name your modules has historically been loose, and the coherence of the module landscape has suffered for it.<br />
<br />
== See also ==<br />
<br />
* [http://www.reddit.com/r/haskell/comments/zdev6/hierarchical_modules_are_frequently_misused/ This article linked on reddit]</div>Benmachinehttps://wiki.haskell.org/User:Benmachine/Overqualified_modulesUser:Benmachine/Overqualified modules2012-12-26T11:41:08Z<p>Benmachine: /* Data.Data.Data */</p>
<hr />
<div>== Overqualified modules ==<br />
<br />
The hierarchical module system was originally proposed as an extension to the Haskell98 standard, and adopted formally in Haskell2010. It is typically regarded as one of the less controversial extensions, because more or less everyone agreed that single-token module names were liable to become a huge tangled mess with everyone stepping on each others' toes.<br />
<br />
=== Data.Data.Data ===<br />
<br />
I lack a little historical context here, since the extension was widespread before I was introduced to Haskell, but I think that the current layout of the module hierarchy is unsatisfactory. Having been given hierarchical modules, Haskellers seem to feel obliged to use them: single-component names are virtually unheard of. Yet in many cases, the additional categorisation seems to add no semantic content whatsoever. What do we learn about a module by its name <tt>Data.Bool</tt> that was not already evident in the <tt>Bool</tt>? Why is the <tt>Functor</tt> type class a piece of <tt>Data</tt> but the closely-related <tt>Applicative</tt> type class a <tt>Control</tt> structure? Why do we have <tt>Data.Monoid</tt> but <tt>Control.Category</tt>?<br />
<br />
=== Redundant specification ===<br />
<br />
There are certainly cases where the additional qualification adds meaning. Writing <hask>import Haskell</hask> at the top of your file seems meaningless, where in <hask>import Haskell.Parser</hask> you have a slightly better idea of what is being requested. However, minimalism is desirable: when adding a component to your module name, ask yourself if it resolves any confusion or prevents any ambiguity. I would argue that in Codec.Binary.UTF8.Generic, for example, nearly all of the name is redundant. There is no UTF-8 that is not a binary codec, and arguably the Generic component of the name is equally unenlightening. Just name the module UTF8, the shortest unambiguous description of its purpose.<br />
<br />
=== Redundant disambiguation ===<br />
<br />
One could argue that keeping module names long reduces the risk of collision. It's true that specifying more information in the module name might reduce the chance of some other module clashing with it, but often people confuse “information content” with “textual length”: clearly, grouping all monad-related modules under Control.Monad instead of just Monad is not going to stop two implementations of Reader from interfering with each other. So keep just the meaningful component of the name: what, after all, could possibly be named Monad except for a module housing the Monad class and related utility functions? Likewise Applicative, List, Exception, IO: all sorts of concepts are clearly going to exist only once in Haskell. Those that don't are no better served being Control.Monad.Reader than Monad.Reader.<br />
<br />
If you really want to avoid name collisions, take a leaf from syb's book: previously under the hierarchy Data.Generics, which not only suffered from Data-itis but also adequately described any generic programming mechanism, syb is starting to move over to the new, more specific Generics.SYB hierarchy. This drops the useless Data prefix and instead uses a component – the name of the package – that is very likely to be unique to this particular design and implementation. We appear to lose some "generality", but in reality the knowledge that you were using SYB in particular was probably already encoded in your program, since other generics libraries will have made different design decisions. The new name also emphasises the position of syb as a generics library, not the generics library – on an equal footing with Uniplate and other similar tools.<br />
<br />
=== Internal package politics ===<br />
<br />
Hierarchical modules do make internal structuring of a project easier; one only needs to look at something like Haskore's module list to see that they could clearly not just all be dumped in a single source directory. So that is a legitimate use, but of course there's not necessarily any reason why the internal structure of your project has to be reflected in the external API you provide. If you want twenty helper modules in various tidy subdirectories, fine, but you can probably re-export everything relevant (and it is good design not to export too much) in just a few root modules at the base of your hierarchy. Don't confuse what makes life easy for the library author with what makes things easy for the library user – and don't assume you need to trade one off against the other.<br />
<br />
=== Some syntactical digressions ===<br />
<br />
In addition to the above practical concerns, I also somewhat object to the overuse of the poor little <hask>.</hask> character. For example, one should in principle be able to write a list of all weekdays as <hask>[Monday..]</hask>, but this actually parses as a qualified reference to the Monday module – you'll need to use the marginally uglier <hask>[Monday ..]</hask>. This also demonstrates how the syntax for qualified operators is just plain ugly. It's hard to write and equally hard to read <hask>7 Prelude.+ 8</hask> or, to really rub it in, <hask>f Control.Category.. g</hask>.<br />
<br />
== Conclusion ==<br />
<br />
Hierarchical modules added some much-needed structure to Haskell's module namespace, but should be used sparingly and responsibly to avoid tragic keyboard wear every time I want to <hask>import qualified Text.ParserCombinators.Parsec.Combinator as PCPC</hask>. The policy on how best to name your modules has historically been loose, and the coherence of the module landscape has suffered for it.<br />
<br />
== See also ==<br />
<br />
* [http://www.reddit.com/r/haskell/comments/zdev6/hierarchical_modules_are_frequently_misused/ This article linked on reddit]</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-22T05:28:24Z<p>Benmachine: /* Syntactic dictionary */</p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml is strict by default, although it has some facility for introducing laziness.<br />
<br />
OCaml's <tt>let</tt> is non-recursive by default, but has the form <tt>let rec</tt> for defining recursive functions.<br />
<br />
OCaml is impure: although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| <br />
| '''Haskell'''<br />
| '''OCaml'''<br />
| '''Comments'''<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data DList a = MkDList ([a] -> [a])<br />
data Either a b = Left a | Right b<br />
|<br />
type 'a dlist = MkDList of ('a list -> 'a list)<br />
type ('a, 'b) either = Left of 'a | Right of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
B x<br />
<nowiki>| x > 0 -> ...<br />
|</nowiki> otherwise -> ...<br />
C a b -> ...<br />
<br />
case Left () of<br />
Left x -> x<br />
Right x -> x<br />
|<br />
match x with<br />
B x when x > 0 -> ...<br />
<nowiki>| B x -> ...<br />
|</nowiki> C (a, b) -> ...<br />
<br />
match Left () with<br />
Left x <nowiki>|</nowiki> Right x -> x<br />
|<br />
|}</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-22T05:27:48Z<p>Benmachine: /* Syntactic dictionary */</p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml is strict by default, although it has some facility for introducing laziness.<br />
<br />
OCaml's <tt>let</tt> is non-recursive by default, but has the form <tt>let rec</tt> for defining recursive functions.<br />
<br />
OCaml is impure: although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| <br />
| '''Haskell'''<br />
| '''OCaml'''<br />
| '''Comments'''<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data DList a = MkDList ([a] -> [a])<br />
data Either a b = Left a | Right b<br />
|<br />
type 'a dlist = MkDList of ('a list -> 'a list)<br />
type ('a, 'b) either = Left of 'a | Right of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
B x<br />
<nowiki>| x > 0 -> ...<br />
|</nowiki> otherwise -> ...<br />
C a b -> ...<br />
<br />
case L () of<br />
L x -> x<br />
R x -> x<br />
|<br />
match x with<br />
B x when x > 0 -> ...<br />
<nowiki>| B x -> ...<br />
|</nowiki> C (a, b) -> ...<br />
<br />
match L () with<br />
L x <nowiki>|</nowiki> R x -> x<br />
|<br />
|}</div>Benmachinehttps://wiki.haskell.org/Multi-parameter_type_classMulti-parameter type class2012-12-21T17:19:51Z<p>Benmachine: /* About */</p>
<hr />
<div>[[Category:Language extensions]]<br />
[[Category:Glossary]]<br />
[[Category:Stub articles]]<br />
== About ==<br />
<br />
Basically, [[type class|type classes]] which can take multiple arguments, such as:<br />
<br />
<haskell><br />
class Monad m => VarMonad m v where<br />
new :: a -> m (v a)<br />
get :: v a -> m a<br />
put :: v a -> a -> m ()<br />
<br />
instance VarMonad IO IORef where ...<br />
instance VarMonad (ST s) (STRef s) where ...<br />
</haskell><br />
<br />
To enable them, use the <hask>{-# LANGUAGE MultiParamTypeClasses #-}</hask> pragma.<br />
<br />
If you think of a single-parameter type class as a set of types, then a multi-parameter type class is a relation between types.<br />
<br />
Naive use of MPTCs may result in ambiguity, so [[functional dependencies]] were developed as a method of resolving that ambiguity, declaring that some subset of the parameters is sufficient to determine the values of the others.<br />
<br />
Some uses of MPTCs with functional dependencies can be replaced with [[type families]].<br />
<br />
== Also see ==<br />
<br />
[http://hackage.haskell.org/trac/haskell-prime/wiki/MultiParamTypeClasses The Haskell' page]</div>Benmachinehttps://wiki.haskell.org/Multi-parameter_type_classMulti-parameter type class2012-12-21T17:18:59Z<p>Benmachine: </p>
<hr />
<div>[[Category:Language extensions]]<br />
[[Category:Glossary]]<br />
[[Category:Stub articles]]<br />
== About ==<br />
<br />
Basically, [[type class|type classes]] which can take multiple arguments, such as:<br />
<br />
<haskell><br />
class Monad m => VarMonad m v where<br />
new :: a -> m (v a)<br />
get :: v a -> m a<br />
put :: v a -> a -> m ()<br />
<br />
instance VarMonad IO IORef where ...<br />
instance VarMonad (ST s) (STRef s) where ...<br />
</haskell><br />
<br />
The correct LANGUAGE pragma for them is <hask>{-# LANGUAGE MultiParamTypeClasses #-}</hask><br />
<br />
If you think of a single-parameter type class as a set of types, then a multi-parameter type class is a relation between types.<br />
<br />
Naive use of MPTCs may result in ambiguity, so [[functional dependencies]] were developed as a method of resolving that ambiguity, declaring that some subset of the parameters is sufficient to determine the values of the others.<br />
<br />
Some uses of MPTCs with functional dependencies can be replaced with [[type families]].<br />
<br />
== Also see ==<br />
<br />
[http://hackage.haskell.org/trac/haskell-prime/wiki/MultiParamTypeClasses The Haskell' page]</div>Benmachinehttps://wiki.haskell.org/Monad_Transformer_LibraryMonad Transformer Library2012-12-21T17:04:33Z<p>Benmachine: /* See also */</p>
<hr />
<div>The MTL provides a selection of [[monad]]s and their [[Monad Transformers Explained|transformer]] variants<br />
along with type classes that allow uniform handling of a base monad and its transformer.<br />
<br />
See the package on [http://hackage.haskell.org/package/mtl/ Hackage].<br />
<br />
Version 2 of the MTL has some small<br />
[[Incompatibilities between MTL 1 and MTL 2|incompatibilities]]<br />
relative to version 1.<br />
See "[[Upgrading from MTL 1 to MTL 2]]" for instructions on how<br />
to make code written for version 1 work with version 2.<br />
<br />
=== History ===<br />
<br />
Once upon a time, mtl was a standalone monad transformer library, that defined monad transformers and constructor classes for them. The constructor classes were frequently [[Multi-parameter type class|multiparameter classes]] with [[functional dependencies]].<br />
<br />
Some time later, [[type families]] were invented, and were found to solve several of the same problems as multiparameter classes with functional dependencies. A package named mtl-tf was developed, to provide the functionality of mtl but using type families instead.<br />
<br />
However, there was a lot of duplicated code involved: mtl and mtl-tf both defined their own monad transformers, so they didn't work well together. The constructor classes were different by necessity, because they used different technology, but the data types themselves were duplicated for no reason.<br />
<br />
Hence, transformers was developed: a library that used no extensions to Haskell98 and only defined the transformer types themselves, so that more advanced libraries could share them as a base. monads-fd and monads-tf were developed as libraries that took transformers from the transformers package and defined the constructor classes over the top of them, monads-fd using multiparameter typeclasses with functional dependencies and monads-tf using type families.<br />
<br />
The technological problem was then solved, but unfortunately the original mtl library already had a lot of traction: it had existed for longer and was in widespread use. So instead of encouraging people to switch libraries, the maintainers switched implementations instead: they decided to merge monads-fd and mtl into a single library.<br />
<br />
Since the mtl name was far better known, monads-fd was deprecated, and mtl was switched to depend on transformers. Since transformers had some stylistic differences as well, this resulted in some API changes (see above).<br />
<br />
As it now stands, transformers is the "standard" monad transformer library, but mtl and monads-tf both act as extensions of it. monads-tf is not very well-used, which is unfortunate as it's quite a nice approach.<br />
<br />
=== See also ===<br />
<br />
* [http://stackoverflow.com/questions/2769487/mtl-transformers-monads-fd-monadlib-and-the-paradox-of-choice Stack Overflow: mtl, transformers, monads-fd, monadLib, and the paradox of choice]<br />
* [http://www.haskell.org/pipermail/libraries/2010-September/014281.html libraries mailing list: Haskell Platform Proposal: add transformers and revise the mtl package to depend on it]<br />
<br />
[[Category:Monad]]</div>Benmachinehttps://wiki.haskell.org/Monad_Transformer_LibraryMonad Transformer Library2012-12-21T16:53:00Z<p>Benmachine: /* History */</p>
<hr />
<div>The MTL provides a selection of [[monad]]s and their [[Monad Transformers Explained|transformer]] variants<br />
along with type classes that allow uniform handling of a base monad and its transformer.<br />
<br />
See the package on [http://hackage.haskell.org/package/mtl/ Hackage].<br />
<br />
Version 2 of the MTL has some small<br />
[[Incompatibilities between MTL 1 and MTL 2|incompatibilities]]<br />
relative to version 1.<br />
See "[[Upgrading from MTL 1 to MTL 2]]" for instructions on how<br />
to make code written for version 1 work with version 2.<br />
<br />
=== History ===<br />
<br />
Once upon a time, mtl was a standalone monad transformer library, that defined monad transformers and constructor classes for them. The constructor classes were frequently [[Multi-parameter type class|multiparameter classes]] with [[functional dependencies]].<br />
<br />
Some time later, [[type families]] were invented, and were found to solve several of the same problems as multiparameter classes with functional dependencies. A package named mtl-tf was developed, to provide the functionality of mtl but using type families instead.<br />
<br />
However, there was a lot of duplicated code involved: mtl and mtl-tf both defined their own monad transformers, so they didn't work well together. The constructor classes were different by necessity, because they used different technology, but the data types themselves were duplicated for no reason.<br />
<br />
Hence, transformers was developed: a library that used no extensions to Haskell98 and only defined the transformer types themselves, so that more advanced libraries could share them as a base. monads-fd and monads-tf were developed as libraries that took transformers from the transformers package and defined the constructor classes over the top of them, monads-fd using multiparameter typeclasses with functional dependencies and monads-tf using type families.<br />
<br />
The technological problem was then solved, but unfortunately the original mtl library already had a lot of traction: it had existed for longer and was in widespread use. So instead of encouraging people to switch libraries, the maintainers switched implementations instead: they decided to merge monads-fd and mtl into a single library.<br />
<br />
Since the mtl name was far better known, monads-fd was deprecated, and mtl was switched to depend on transformers. Since transformers had some stylistic differences as well, this resulted in some API changes (see above).<br />
<br />
As it now stands, transformers is the "standard" monad transformer library, but mtl and monads-tf both act as extensions of it. monads-tf is not very well-used, which is unfortunate as it's quite a nice approach.<br />
<br />
=== See also ===<br />
<br />
* [http://stackoverflow.com/questions/2769487/mtl-transformers-monads-fd-monadlib-and-the-paradox-of-choice Stack Overflow: mtl, transformers, monads-fd, monadLib, and the paradox of choice]<br />
<br />
[[Category:Monad]]</div>Benmachinehttps://wiki.haskell.org/Monad_Transformer_LibraryMonad Transformer Library2012-12-21T16:49:21Z<p>Benmachine: History as I understand it</p>
<hr />
<div>The MTL provides a selection of [[monad]]s and their [[Monad Transformers Explained|transformer]] variants<br />
along with type classes that allow uniform handling of a base monad and its transformer.<br />
<br />
See the package on [http://hackage.haskell.org/package/mtl/ Hackage].<br />
<br />
Version 2 of the MTL has some small<br />
[[Incompatibilities between MTL 1 and MTL 2|incompatibilities]]<br />
relative to version 1.<br />
See "[[Upgrading from MTL 1 to MTL 2]]" for instructions on how<br />
to make code written for version 1 work with version 2.<br />
<br />
=== History ===<br />
<br />
Once upon a time, mtl was a standalone monad transformer library, that defined monad transformers and constructor classes for them. The constructor classes were frequently [[Multi-parameter type class|multiparameter classes]] with [[functional dependencies]].<br />
<br />
Some time later, [[type families]] were invented, and were found to solve several of the same problems as multiparameter classes with functional dependencies. A package named mtl-tf was developed, to provide the functionality of mtl but using type families instead.<br />
<br />
However, there was a lot of duplicated code involved: mtl and mtl-tf both defined their own monad transformers, so they didn't work well together. The constructor classes were different by necessity, because they used different technology, but the data types themselves were duplicated for no reason.<br />
<br />
Hence, transformers was developed: a library that used no extensions to Haskell98 and only defined the transformer types themselves, so that more advanced libraries could share them as a base. monads-fd and monads-tf were developed as libraries that took transformers from the transformers package and defined the constructor classes over the top of them, monads-fd using multiparameter typeclasses with functional dependencies and monads-tf using type families.<br />
<br />
The technological problem was then solved, but unfortunately the original mtl library already had a lot of traction: it had existed for longer and was in widespread use. So instead of encouraging people to switch libraries, the maintainers switched implementations instead: they decided to merge monads-fd and mtl into a single library.<br />
<br />
Since the mtl name was far better known, monads-fd was deprecated, and mtl was switched to depend on transformers. Since transformers had some stylistic differences as well, this resulted in some API changes (see above).<br />
<br />
As it now stands, transformers is the "Standard" monad transformer library, but mtl and monads-tf both act as extensions of it. monads-tf is not very well-used, which is unfortunate as it's quite a nice approach.<br />
<br />
=== See also ===<br />
<br />
* [http://stackoverflow.com/questions/2769487/mtl-transformers-monads-fd-monadlib-and-the-paradox-of-choice Stack Overflow: mtl, transformers, monads-fd, monadLib, and the paradox of choice]<br />
<br />
[[Category:Monad]]</div>Benmachinehttps://wiki.haskell.org/Haddock/Development_ideasHaddock/Development ideas2012-12-17T12:19:29Z<p>Benmachine: Removing ideas that are now implemented or irrelevant.</p>
<hr />
<div>Most of these ideas are '''very''' old, but some may still be relevant.<br />
<br />
* It would be good to have a recursive flag that would operate on all the .hs and .lhs files under a single directory.<br />
* Haddock should emit the documentation about instances. For example, it's important to document that the Data.Map instance of Foldable only folds over the values and not the keys.<br />
* There should be an annotation to include a function's entire definition in the documentation. This would be useful for functions like <hask>(.)</hask> and <hask>mapM</hask> where the definition is the clearest possible documentation, and for QuickCheck properties that specify the behavior of a library.<br />
* There should be an option to include a simplified implementation of a function that is equivalent to the one in the code. For instance, instead of showing a complex implementation of List.length that makes use of stream fusion we could show a simple one based on foldl'.<br />
* Optionally [http://www.haskell.org/pipermail/haskell-cafe/2008-January/038211.html show qualifications of identifiers], that is print <hask>Sequence.map</hask> rather than <hask>map</hask>, <hask>Music.T</hask> rather than just <hask>T</hask>. The option for haddock could be <code>--qualification QUAL</code><br />
** <code>none</code> (default) strip off qualification (just <hask>map</hask>)<br />
** <code>orig</code> show the identifiers as they are written in the module (e.g. <hask>map</hask> or <hask>List.map</hask>)<br />
** <code>full</code> show all identifiers with full qualification (<hask>Data.List.map</hask>)</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-12T18:11:25Z<p>Benmachine: /* Syntactic dictionary */</p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml is strict by default, although it has some facility for introducing laziness.<br />
<br />
OCaml's <tt>let</tt> is non-recursive by default, but has the form <tt>let rec</tt> for defining recursive functions.<br />
<br />
OCaml is impure: although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| <br />
| '''Haskell'''<br />
| '''OCaml'''<br />
| '''Comments'''<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data DList a = MkDList ([a] -> [a])<br />
data Either a b = Left a | Right b<br />
|<br />
type 'a dlist = MkDList of ('a list -> 'a list)<br />
type ('a, 'b) either = Left of 'a | Right of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
B x<br />
<nowiki>| x > 0 -> ...<br />
|</nowiki> otherwise -> ...<br />
C a b -> ...<br />
<br />
case L () of<br />
L x -> x<br />
R x -> x<br />
|<br />
match x with<br />
B x when x > 0 -> ...<br />
B x -> ...<br />
<nowiki>|</nowiki> C (a, b) -> ...<br />
<br />
match L () with<br />
L x <nowiki>|</nowiki> R x -> x<br />
|<br />
|}</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-12T18:10:08Z<p>Benmachine: </p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml is strict by default, although it has some facility for introducing laziness.<br />
<br />
OCaml's <tt>let</tt> is non-recursive by default, but has the form <tt>let rec</tt> for defining recursive functions.<br />
<br />
OCaml is impure: although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| <br />
| '''Haskell'''<br />
| '''OCaml'''<br />
| '''Comments'''<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data D a = MkD (a -> a)<br />
data E a b = L a | R b<br />
|<br />
type 'a d = MkD of ('a -> 'a)<br />
type ('a, 'b) e = L of 'a | R of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
B x<br />
<nowiki>| x > 0 -> ...<br />
|</nowiki> otherwise -> ...<br />
C a b -> ...<br />
<br />
case L () of<br />
L x -> x<br />
R x -> x<br />
|<br />
match x with<br />
B x when x > 0 -> ...<br />
B x -> ...<br />
<nowiki>|</nowiki> C (a, b) -> ...<br />
<br />
match L () with<br />
L x <nowiki>|</nowiki> R x -> x<br />
|<br />
|}</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-12T18:09:18Z<p>Benmachine: </p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml is strict by default, although it has some facility for introducing laziness.<br />
<br />
OCaml's <tt>let</tt> is non-recursive by default, but has the form <tt>let rec</tt> for defining recursive functions.<br />
<br />
OCaml is impure: although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| <br />
| '''Haskell'''<br />
| '''OCaml'''<br />
| '''Comments'''<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data D a = MkD (a -> a)<br />
data E a b = L a | R b<br />
|<br />
type 'a d = MkD of ('a -> 'a)<br />
type ('a, 'b) e = L of 'a | R of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
B x<br />
<nowiki>| x > 0 -> ...<br />
|</nowiki> otherwise -> ...<br />
C a b -> ...<br />
<br />
case L () of<br />
L x -> x<br />
R x -> x<br />
|<br />
match x with<br />
B x when x > 0 -> ...<br />
B x -> ...<br />
<nowiki>|</nowiki> C (a, b) -> ...<br />
<br />
match L () with<br />
L x <nowiki>|</nowiki> R x -> x<br />
|<br />
|}</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-12T13:29:01Z<p>Benmachine: /* Syntactic dictionary */</p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| <br />
| '''Haskell'''<br />
| '''OCaml'''<br />
| '''Comments'''<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data D a = MkD (a -> a)<br />
data E a b = L a | R b<br />
|<br />
type 'a d = MkD of ('a -> 'a)<br />
type ('a, 'b) e = L of 'a | R of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
B x<br />
<nowiki>| x > 0 -> ...<br />
|</nowiki> otherwise -> ...<br />
C a b -> ...<br />
<br />
case L () of<br />
L x -> x<br />
R x -> x<br />
|<br />
match x with<br />
B x when x > 0 -> ...<br />
B x -> ...<br />
<nowiki>|</nowiki> C (a, b) -> ...<br />
<br />
match L () with<br />
L x <nowiki>|</nowiki> R x -> x<br />
|<br />
|}<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml is strict by default, although it has some facility for introducing laziness.<br />
<br />
OCaml's <tt>let</tt> is non-recursive by default, but has the form <tt>let rec</tt> for defining recursive functions.<br />
<br />
OCaml is impure: although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-12T13:27:14Z<p>Benmachine: /* Syntactic dictionary */</p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| <br />
| '''Haskell'''<br />
| '''OCaml'''<br />
| '''Comments'''<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data D a = D (a -> a)<br />
data E a b = L a | R b<br />
|<br />
type 'a d = D of ('a -> 'a)<br />
type ('a, 'b) e = L of 'a | R of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
B x<br />
<nowiki>| x > 0 -> ...<br />
|</nowiki> otherwise -> ...<br />
C a b -> ...<br />
<br />
case L () of<br />
L x -> x<br />
R x -> x<br />
|<br />
match x with<br />
B x when x > 0 -> ...<br />
B x -> ...<br />
<nowiki>|</nowiki> C (a, b) -> ...<br />
<br />
match L () with<br />
L x <nowiki>|</nowiki> R x -> x<br />
|<br />
|}<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml is strict by default, although it has some facility for introducing laziness.<br />
<br />
OCaml's <tt>let</tt> is non-recursive by default, but has the form <tt>let rec</tt> for defining recursive functions.<br />
<br />
OCaml is impure: although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-12T13:22:38Z<p>Benmachine: /* Syntactic dictionary */</p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| <br />
| '''Haskell'''<br />
| '''OCaml'''<br />
| '''Comments'''<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data D a = D (a -> a)<br />
data E a b = L a | R b<br />
|<br />
type 'a d = D of ('a -> 'a)<br />
type ('a, 'b) e = L of 'a | R of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
A x<br />
<nowiki>|</nowiki> x > 0 -> ...<br />
C a b -> ...<br />
|<br />
match x with<br />
B x when x > 0 -> ...<br />
<nowiki>|</nowiki> C (a, b) -> ...<br />
| There doesn't seem to be syntax for multiple guards<br />
|}<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml is strict by default, although it has some facility for introducing laziness.<br />
<br />
OCaml's <tt>let</tt> is non-recursive by default, but has the form <tt>let rec</tt> for defining recursive functions.<br />
<br />
OCaml is impure: although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-12T13:22:19Z<p>Benmachine: /* Syntactic dictionary */</p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| <br />
| '''Haskell'''<br />
| '''OCaml'''<br />
| '''Comments'''<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data D a = D (a -> a)<br />
data E a b = L a | R b<br />
|<br />
type 'a d = D of ('a -> 'a)<br />
type ('a, 'b) e = L of 'a | R of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
A x<br />
<nowiki>|</nowiki> x > 0 -> ...<br />
C a b -> ...<br />
|<br />
match x with<br />
B x when x > 0 -> ...<br />
| C (a, b) -> ...<br />
| There doesn't seem to be syntax for multiple guards<br />
|}<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml is strict by default, although it has some facility for introducing laziness.<br />
<br />
OCaml's <tt>let</tt> is non-recursive by default, but has the form <tt>let rec</tt> for defining recursive functions.<br />
<br />
OCaml is impure: although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-12T13:21:39Z<p>Benmachine: /* Syntactic dictionary */</p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| <br />
| '''Haskell'''<br />
| '''OCaml'''<br />
| '''Comments'''<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data D a = D (a -> a)<br />
data E a b = L a | R b<br />
|<br />
type 'a d = D of ('a -> 'a)<br />
type ('a, 'b) e = L of 'a | R of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
A x<br />
<nowiki>|</nowiki> x > 0 -> ...<br />
C a b -> ...<br />
|<br />
match x with<br />
B x when x > 0 -> ...<br />
C (a, b) -> ...<br />
| There doesn't seem to be syntax for multiple guards<br />
|}<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml is strict by default, although it has some facility for introducing laziness.<br />
<br />
OCaml's <tt>let</tt> is non-recursive by default, but has the form <tt>let rec</tt> for defining recursive functions.<br />
<br />
OCaml is impure: although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-12T01:01:06Z<p>Benmachine: /* Syntactic dictionary */</p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| Language<br />
| Haskell<br />
| OCaml<br />
| Comments<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data D a = D (a -> a)<br />
data E a b = L a | R b<br />
|<br />
type 'a d = D of ('a -> 'a)<br />
type ('a, 'b) e = L of 'a | R of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
A x<br />
<nowiki>|</nowiki> x > 0 -> ...<br />
C a b -> ...<br />
|<br />
match x with<br />
B x when x > 0 -> ...<br />
C (a, b) -> ...<br />
| There doesn't seem to be syntax for multiple guards<br />
|}<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml is strict by default, although it has some facility for introducing laziness.<br />
<br />
OCaml's <tt>let</tt> is non-recursive by default, but has the form <tt>let rec</tt> for defining recursive functions.<br />
<br />
OCaml is impure: although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-12T00:16:23Z<p>Benmachine: /* Syntactic dictionary */</p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| Language<br />
| Haskell<br />
| OCaml<br />
| Comments<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data D a = D (a -> a)<br />
data E a b = L a | R b<br />
|<br />
type 'a d = D of ('a -> 'a)<br />
type ('a, 'b) e = L of 'a | R of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
A x<br />
<nowiki>|</nowiki> x == 0 -> ...<br />
C a b -> ...<br />
|<br />
match x with<br />
B x when x = 0 -> ...<br />
C (a, b) -> ...<br />
| There doesn't seem to be syntax for more guards<br />
|}<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml is strict by default, although it has some facility for introducing laziness.<br />
<br />
OCaml's <tt>let</tt> is non-recursive by default, but has the form <tt>let rec</tt> for defining recursive functions.<br />
<br />
OCaml is impure: although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-11T23:09:24Z<p>Benmachine: /* Conceptual differences */</p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| Language<br />
| Haskell<br />
| OCaml<br />
| Comments<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data D a = D (a -> a)<br />
data E a b = L a | R b<br />
|<br />
type 'a d = D of ('a -> 'a)<br />
type ('a, 'b) e = L of 'a | R of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
A x -> ...<br />
C a b -> ...<br />
|<br />
match x with<br />
B x -> ...<br />
C (a, b) -> ...<br />
|}<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml is strict by default, although it has some facility for introducing laziness.<br />
<br />
OCaml's <tt>let</tt> is non-recursive by default, but has the form <tt>let rec</tt> for defining recursive functions.<br />
<br />
OCaml is impure: although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-11T23:09:12Z<p>Benmachine: /* Conceptual differences */</p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| Language<br />
| Haskell<br />
| OCaml<br />
| Comments<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data D a = D (a -> a)<br />
data E a b = L a | R b<br />
|<br />
type 'a d = D of ('a -> 'a)<br />
type ('a, 'b) e = L of 'a | R of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
A x -> ...<br />
C a b -> ...<br />
|<br />
match x with<br />
B x -> ...<br />
C (a, b) -> ...<br />
|}<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml is strict by default, although it has some facility for introducing laziness.<br />
<br />
OCaml's <tt>let</tt> is non-recursive by default, but has the form <tt>let rec</tt> for defining recursive functions.<br />
<br />
OCaml is ''impure''. Although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-11T23:08:21Z<p>Benmachine: /* Conceptual differences */</p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| Language<br />
| Haskell<br />
| OCaml<br />
| Comments<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data D a = D (a -> a)<br />
data E a b = L a | R b<br />
|<br />
type 'a d = D of ('a -> 'a)<br />
type ('a, 'b) e = L of 'a | R of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
A x -> ...<br />
C a b -> ...<br />
|<br />
match x with<br />
B x -> ...<br />
C (a, b) -> ...<br />
|}<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml's <tt>let</tt> is non-recursive and strict by default, but has keywords <tt>rec</tt> (as in <tt>let rec</tt>) and <tt>lazy</tt> to introduce more Haskellish behaviour.<br />
<br />
OCaml is ''impure''. Although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.</div>Benmachinehttps://wiki.haskell.org/OCamlOCaml2012-12-11T23:08:03Z<p>Benmachine: /* Syntactic differences */</p>
<hr />
<div>'''OCaml''' is a functional programming language in the ML family, an extension of the Caml language with object-oriented constructs.<br />
<br />
This page aims to cover some of its differences from Haskell.<br />
<br />
== Syntactic dictionary ==<br />
<br />
{| class="wikitable"<br />
| Language<br />
| Haskell<br />
| OCaml<br />
| Comments<br />
|-<br />
| Anonymous functions<br />
|<br />
\x y -> ...<br />
|<br />
fun x y -> ...<br />
|<br />
|-<br />
| Multiple assignments<br />
|<br />
let<br />
x = 4<br />
y = 5<br />
in ...<br />
|<br />
let x = 4<br />
and y = 5<br />
in ...<br />
|<br />
|-<br />
| Types<br />
|<br />
Int, Bool, (Double, Char), a<br />
|<br />
int, bool, float * char, 'a<br />
| <tt>float</tt> is a double type<br />
|-<br />
| Type signatures<br />
|<br />
const :: a -> b -> a<br />
|<br />
const : 'a -> 'b -> 'a<br />
| Signatures usually omitted in OCaml<br />
|-<br />
| Type declarations<br />
|<br />
data A = B Int | C Char Bool<br />
x = B 3<br />
y = C 'a' True<br />
|<br />
type a = B of int | C of char * bool<br />
let x = B 3<br />
and y = C ('a', true)<br />
|<br />
|-<br />
| Parametrised types<br />
|<br />
data D a = D (a -> a)<br />
data E a b = L a | R b<br />
|<br />
type 'a d = D of ('a -> 'a)<br />
type ('a, 'b) e = L of 'a | R of 'b<br />
|-<br />
| Pattern matching<br />
|<br />
case x of<br />
A x -> ...<br />
C a b -> ...<br />
|<br />
match x with<br />
B x -> ...<br />
C (a, b) -> ...<br />
|}<br />
<br />
== Conceptual differences ==<br />
<br />
OCaml's <tt>let</tt> is non-recursive and strict by default, but has keywords <tt>rec</tt> (as in <tt>let rec</tt>) and <tt>lazy</tt> to introduce the Haskell behaviour.<br />
<br />
OCaml is ''impure''. Although it makes heavy use of immutable data, it also has mutable references and arrays available, and IO is performed by ordinary functions.</div>Benmachine