https://wiki.haskell.org/api.php?action=feedcontributions&user=Lspitzner&feedformat=atomHaskellWiki - User contributions [en]2024-03-29T05:48:56ZUser contributionsMediaWiki 1.35.5https://wiki.haskell.org/index.php?title=Data.Foldable.foldr&diff=62209Data.Foldable.foldr2017-11-15T12:58:41Z<p>Lspitzner: Use unsugared-list in example</p>
<hr />
<div>The <strong><hask>foldr</hask></strong> function applies a function against an accumulator and each value of a <hask>Foldable</hask> structure from right to left, folding it to a single value. <hask>foldr</hask> is a method of the <hask>Foldable</hask> typeclass:<br />
<pre><br />
foldr (++) [] [[0, 1], [2, 3], [4, 5]] <br />
-- returns [0, 1, 2, 3, 4, 5]<br />
</pre><br />
<br />
See also [[Data.Foldable.foldl]] for a left-to-right fold. <hask>Data.Foldable.foldr</hask> is a generic version of [[Data.List.foldr]]<br />
<br />
== Syntax ==<br />
=== Type Signature ===<br />
<br />
<pre><br />
class Foldable t where<br />
foldr :: (a -> b -> b) -> b -> t a -> b<br />
</pre><br />
<br />
=== Invocation ===<br />
<br />
<pre><br />
foldr callback initialValue structure<br />
</pre><br />
<br />
=== Parameters ===<br />
<br />
<pre>callback :: (a -> b -> b)</pre><br />
:Function to execute on each value in the array, this function takes two arguments:<br />
<br />
:<pre>currentValue :: a</pre><br />
::The current element being processed in the structure.<br />
<br />
:<pre>previousValue :: b</pre><br />
::The value returned in the last invocation of <hask>callback</hask> or, <hask>initialValue</hask> if this is the first invocation.<br />
<br />
<pre>initialValue :: b</pre><br />
:the value to use as the second argument of the first call of <hask>callback</hask>. If <hask>foldr</hask> is called with an empty structure for <hask>structure</hask>, then it will simply return <hask>initialValue</hask>.<br />
<br />
<pre>structure :: t a</pre><br />
:a structure which will be iterated through from right to left.<br />
<br />
=== Return Value ===<br />
<br />
The final value that results from the fold.<br />
<br />
== Description ==<br />
<br />
<hask>foldr</hask> will execute the callback function once for each element in the structure. The result will be passed to the next invocation of the callback. For the initial call to <hask>callback</hask>, <hask>previousValue</hask> will be <hask>initialValue</hask>, <hask>currentValue</hask> will be the last element of the structure. For example:<br />
<pre><br />
foldr (+) 4 [0, 1, 2, 3]<br />
-- alternatively written without syntactic sugar for lists:<br />
foldr (+) 4 (0 : (1 : (2 : (3 : []))))<br />
</pre><br />
would be equivalent to:<br />
<pre><br />
0 + (1 + (2 + (3 + 4)))<br />
</pre><br />
Note how <hask>foldr</hask> essentially replaces the <hask>(:)</hask> constructor with some other function (in this case <hask>(+)</hask>).<br />
Or more generally:<br />
<pre><br />
foldr cb iv [x1, x2, ..., xn]<br />
</pre><br />
is equivalent to:<br />
<pre><br />
x1 `cb` (x2 `cb` ... (xn `cb` iv)...)<br />
</pre><br />
with the initial call to callback being the deepest nested in parenthesis.<br />
<br />
For certain values, <hask>callback</hask> may ignore <hask>previousValue</hask>, in which case, due to lazy evaluation, <hask>foldr</hask> will terminate early without calling <hask>callback</hask> for every element. This is useful for operations on infinite lists. Here is a contrived example demonstrating this:<br />
<br />
<pre><br />
foldr go [] [1..] where<br />
go curr prev<br />
| curr > 10 = []<br />
| otherwise = (curr : prev)<br />
-- returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]<br />
</pre><br />
<br />
In this case, the <hask>[]</hask> is ignored, we could have written:<br />
<br />
<pre><br />
foldr go [1,5, 6, 7] [1..] where<br />
go curr prev<br />
| curr > 10 = []<br />
| otherwise = (curr : prev)<br />
</pre><br />
<br />
and achieved the same result.<br />
<br />
Given an empty structure <hask>foldr</hask> will return <hask>initialValue</hask><br />
<br />
== Examples ==<br />
<br />
=== Sum all elements in a list ===<br />
<br />
<pre><br />
list = [1..100]<br />
foldr (+) 0 list -- returns 5050<br />
</pre><br />
<br />
=== Reverse a list ===<br />
<br />
<pre><br />
list = [1..10]<br />
foldr (\x xs -> xs ++ [x]) [] list<br />
</pre><br />
<br />
=== flatten a <hask>Set [a]</hask> to a <hask>Set a</hask> ===<br />
<br />
<pre><br />
import qualified Data.Set as S<br />
<br />
mySet = S.fromList [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]<br />
size mySet -- returns 4<br />
show mySet -- returns "fromList [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]"<br />
<br />
flatSet = foldr (\curr prev -> S.union (S.fromList curr) prev) S.empty mySet<br />
size flatSet -- returns 12<br />
show flatSet -- returns "fromList [1,2,3,4,5,6,7,8,9,10,11,12]"<br />
</pre><br />
<br />
== See Also ==<br />
<br />
* [[Data.Foldable]] a typeclass for structures which can be folded<br />
* [[Data.Foldable.foldl]] similar to <hask>foldr</hask> but starts from the left instead of the right<br />
* [[Data.Foldable.foldr']] a strict version of <hask>foldr</hask><br />
* [[Data.List.foldr]] a list specific version of <hask>foldr</hask><br />
<br />
[[Category:Reference]]</div>Lspitznerhttps://wiki.haskell.org/index.php?title=Package_versioning_policy&diff=60787Package versioning policy2016-05-21T22:25:05Z<p>Lspitzner: Make lexicographic ordering examples match A.B.C pattern</p>
<hr />
<div>== Rationale ==<br />
<br />
The goal of a versioning system is to inform clients of a package of changes to that package that might affect them, and to provide a way for clients to specify a particular version or range of versions of a dependency that they are compatible with.<br />
<br />
[http://haskell.org/cabal Cabal] provides the raw materials for versioning: it allows packages to specify their own version, and it allows dependencies that specify which versions of the dependent package are acceptable. Cabal will select dependencies based on the constraints.<br />
<br />
What is missing from this picture is a ''policy'' that tells the library developer how to set their version numbers, and tells a client how to write a dependency that means their package will not try to compile against an incompatible dependency. For some time there has been an informal policy in use in the Haskell community, but it became clear that we were running into trouble with incorrectly-specified dependencies and unbuildable packages, so this page is an attempt to formalize the policy.<br />
<br />
== Version numbers ==<br />
<br />
[[File:PVP.svg|thumb|A handy unfinished (!) draft of a reference describing the PVP decision tree]]<br />
<br />
A package version number should have the form ''A.B.C'', and may optionally have any number of additional components, for example 2.1.0.4 (in this case, ''A''=2, ''B''=1, ''C=0''). This policy defines the meaning of the first three components ''A-C'', the other components can be used in any way the package maintainer sees fit.<br />
<br />
Version number ordering is already defined by Cabal as the lexicographic ordering of the components. For example, 2.0.1 > 1.3.2, and 2.0.1.0 > 2.0.1. (The <tt>Data.Version.Version</tt> type and its <tt>Ord</tt> instance embody this ordering).<br />
<br />
''A.B'' is known as the ''major'' version number, and ''C'' the ''minor'' version number. When a package is updated, the following rules govern how the version number must change relative to the previous version:<br />
<br />
# If any entity was removed, or the types of any entities or the definitions of datatypes or classes were changed, or [[orphan instance]]s were added or any instances were removed, then the new ''A.B'' must be greater than the previous ''A.B''. Note that modifying imports or depending on a newer version of another package may cause extra orphan instances to be exported and thus force a major version change.<br />
# Otherwise, if only new bindings, types, classes, non-orphan instances or modules (but see below) were added to the interface, then ''A.B'' may remain the same but the new ''C'' must be greater than the old ''C''. Note that modifying imports or depending on a newer version of another package may cause extra non-orphan instances to be exported and thus force a minor version change.<br />
# Otherwise, ''A.B.C'' may remain the same (other version components may change).<br />
<br />
Hence ''A.B.C'' uniquely identifies the API. A client that wants to specify that they depend on a particular version of the API can specify a particular ''A.B.C'' and be sure of getting that API only. For example, <tt>build-depends: mypkg >= 2.1.1 && < 2.1.2</tt>.<br />
<br />
Often a package maintainer wants to add to an API without breaking backwards compatibility, and in that case they can follow the rules of point 2, and increase only ''C''. A client can specify that they are [[Import modules properly|insensitive to additions to the API]] by allowing a range of ''C'' values, e.g. <tt>build-depends: base >= 2.1.1 && < 2.2</tt>.<br />
<br />
If a package defines an orphan instance, it must depend on the minor version of the packages that define the data type and the type class to be backwards compatible. For example, <tt>build-depends: mypkg >= 2.1.1 && < 2.1.2</tt>.<br />
<br />
=== Deprecation ===<br />
<br />
Deprecated entities (via a <tt>DEPRECATED</tt> pragma) should probably be counted as removed for the purposes of upgrading the API, because packages that use <tt>-Werror</tt> will be broken by the deprecation.<br />
<br />
=== Adding new modules ===<br />
<br />
Adding new modules might cause an unavoidable name collision in dependent code. However, this is usually pretty unlikely, especially if you keep to your own namespace, so only an increase of the minor version number is required. If, however, your added module name is taken from another package (e.g. when <tt>network-bytestring</tt> was merged into <tt>network</tt>) or is quite general (<tt>Data.Set</tt> or something similar) then the version increase should be major.<br />
<br />
=== Leaking instances ===<br />
<br />
There is a case where addition or removal of an instance in a package, that the user doesn't depend on directly, can still lead to compilation failures. Consider these three packages:<br />
<br />
Package A:<br />
<haskell><br />
module PackageA where<br />
<br />
class Monad m => MonadLogger m<br />
instance MonadLogger IO<br />
</haskell><br />
<br />
Package B, depends on package A:<br />
<haskell><br />
module PackageB where<br />
<br />
import PackageA<br />
<br />
f :: MonadLogger m => Int -> m String<br />
f = return . show<br />
</haskell><br />
<br />
Package C, depends on package B:<br />
<haskell><br />
module Package C where<br />
<br />
import PackageB<br />
<br />
main :: IO ()<br />
main = f 5 >>= print<br />
</haskell><br />
<br />
Now consider this scenario:<br />
<br />
# Package A removes the <hask>IO</hask> instance and gets its major version number bumped, as required by the PVP.<br />
# Package B, which can still work with the old and new version of package A, changes its dependency on package A to allow for both versions. Package B only gets a patch-level bump.<br />
# Package C might or might not compile, depending on which patch-level version of package B is used.<br />
<br />
The PVP could require that package B bumps its major version number as it now (re-)exports one fewer instances. This will however require more frequent version bumps in the whole ecosystem. As a pragmatic solution, for now the PVP doesn't required a major version bump in this case and instead leaves it to package C to add a dependency on package A to handle this situation.<br />
<br />
=== Version tags ===<br />
<br />
The components of the version number must be numbers! Historically Cabal supported version numbers with string tags at the end, e.g. <tt>1.0-beta</tt> This proved not to work well because the ordering for tags was not well defined. Version tags are [https://github.com/haskell/cabal/issues/890 no longer supported] and mostly ignored, however some tools will fail in some circumstances if they encounter them.<br />
<br />
This can sometimes trip you up if you accidentally stumble into using the deprecated tags syntax without realising it, for example a version number with a date like <tt>1.0.2014-01-27</tt> would be interpreted as the version <tt>1.0.2014</tt> with tags <tt>01</tt> and <tt>27</tt>.<br />
<br />
== Dependencies in Cabal ==<br />
<br />
When publishing a Cabal package, you should ensure that your dependencies in the <tt>build-depends</tt> field are accurate. This means specifying not only lower bounds, but also upper bounds on every dependency. <br />
<br />
At some point in the future, Hackage may refuse to accept packages that do not follow this convention. The aim is that before this happens, we will put in place tool support that makes it easier to follow the convention and less painful when dependencies are updated.<br />
<br />
To minimize breakage when new package versions are released, you can use dependencies that are insensitive to minor version changes (e.g. <tt>foo >= 1.2.1 && < 1.3</tt>). However, note that this approach is slightly risky: when a package exports more things than before, there is a chance that your code will fail to compile due to new name-clash errors. The risk from new name clashes may be small, but you are on the safe side if you [[Import modules properly|import identifiers explicitly or using qualification]].<br />
<br />
== Version syntax ==<br />
<br />
Since Cabal 1.6, you can specify an exact API version according to this policy with the special syntax <tt>package == 1.1.4.*</tt> or an API version up to additions with <tt>package == 1.1.*</tt>. The former translates into <tt>package >= 1.1.4 && < 1.1.5</tt>, for example - notice that 1.1.4 ''is'' included, rather than just including 1.1.4.0.<br />
<br />
== Tools ==<br />
<br />
* script to check for API changes in gtk2hs: http://code.haskell.org/gtk2hs/tools/apidiff/<br />
* [http://hackage.haskell.org/package/precis precis] - a simple tool for a first approximation of package API differences, see the [http://www.haskell.org/pipermail/haskell-cafe/2010-April/077023.html announcement]<br />
* {{HackagePackage|id=check-pvp}} is a program that checks for consistency between package dependencies and import style.<br />
<br />
== Related ==<br />
<br />
* [[Sven Moritz Hallberg]], "[[The_Monad.Reader/Issue2/EternalCompatibilityInTheory|Eternal compatibility in theory]]," [[The Monad.Reader]], [[The Monad.Reader/Issue2|Issue 2]]<br />
* [http://semver.org/ Semantic Versioning] is similar, but allows for version tags and defines how tags affect the ordering.</div>Lspitznerhttps://wiki.haskell.org/index.php?title=Package_versioning_policy&diff=60786Package versioning policy2016-05-21T17:27:50Z<p>Lspitzner: add a note about the decision tree graphic being unfinished</p>
<hr />
<div>== Rationale ==<br />
<br />
The goal of a versioning system is to inform clients of a package of changes to that package that might affect them, and to provide a way for clients to specify a particular version or range of versions of a dependency that they are compatible with.<br />
<br />
[http://haskell.org/cabal Cabal] provides the raw materials for versioning: it allows packages to specify their own version, and it allows dependencies that specify which versions of the dependent package are acceptable. Cabal will select dependencies based on the constraints.<br />
<br />
What is missing from this picture is a ''policy'' that tells the library developer how to set their version numbers, and tells a client how to write a dependency that means their package will not try to compile against an incompatible dependency. For some time there has been an informal policy in use in the Haskell community, but it became clear that we were running into trouble with incorrectly-specified dependencies and unbuildable packages, so this page is an attempt to formalize the policy.<br />
<br />
== Version numbers ==<br />
<br />
[[File:PVP.svg|thumb|A handy unfinished (!) draft of a reference describing the PVP decision tree]]<br />
<br />
A package version number should have the form ''A.B.C'', and may optionally have any number of additional components, for example 2.1.0.4 (in this case, ''A''=2, ''B''=1, ''C=0''). This policy defines the meaning of the first three components ''A-C'', the other components can be used in any way the package maintainer sees fit.<br />
<br />
Version number ordering is already defined by Cabal as the lexicographic ordering of the components. For example, 2.1 > 1.3, and 2.1.1 > 2.1. (The <tt>Data.Version.Version</tt> type and its <tt>Ord</tt> instance embody this ordering).<br />
<br />
''A.B'' is known as the ''major'' version number, and ''C'' the ''minor'' version number. When a package is updated, the following rules govern how the version number must change relative to the previous version:<br />
<br />
# If any entity was removed, or the types of any entities or the definitions of datatypes or classes were changed, or [[orphan instance]]s were added or any instances were removed, then the new ''A.B'' must be greater than the previous ''A.B''. Note that modifying imports or depending on a newer version of another package may cause extra orphan instances to be exported and thus force a major version change.<br />
# Otherwise, if only new bindings, types, classes, non-orphan instances or modules (but see below) were added to the interface, then ''A.B'' may remain the same but the new ''C'' must be greater than the old ''C''. Note that modifying imports or depending on a newer version of another package may cause extra non-orphan instances to be exported and thus force a minor version change.<br />
# Otherwise, ''A.B.C'' may remain the same (other version components may change).<br />
<br />
Hence ''A.B.C'' uniquely identifies the API. A client that wants to specify that they depend on a particular version of the API can specify a particular ''A.B.C'' and be sure of getting that API only. For example, <tt>build-depends: mypkg >= 2.1.1 && < 2.1.2</tt>.<br />
<br />
Often a package maintainer wants to add to an API without breaking backwards compatibility, and in that case they can follow the rules of point 2, and increase only ''C''. A client can specify that they are [[Import modules properly|insensitive to additions to the API]] by allowing a range of ''C'' values, e.g. <tt>build-depends: base >= 2.1.1 && < 2.2</tt>.<br />
<br />
If a package defines an orphan instance, it must depend on the minor version of the packages that define the data type and the type class to be backwards compatible. For example, <tt>build-depends: mypkg >= 2.1.1 && < 2.1.2</tt>.<br />
<br />
=== Deprecation ===<br />
<br />
Deprecated entities (via a <tt>DEPRECATED</tt> pragma) should probably be counted as removed for the purposes of upgrading the API, because packages that use <tt>-Werror</tt> will be broken by the deprecation.<br />
<br />
=== Adding new modules ===<br />
<br />
Adding new modules might cause an unavoidable name collision in dependent code. However, this is usually pretty unlikely, especially if you keep to your own namespace, so only an increase of the minor version number is required. If, however, your added module name is taken from another package (e.g. when <tt>network-bytestring</tt> was merged into <tt>network</tt>) or is quite general (<tt>Data.Set</tt> or something similar) then the version increase should be major.<br />
<br />
=== Leaking instances ===<br />
<br />
There is a case where addition or removal of an instance in a package, that the user doesn't depend on directly, can still lead to compilation failures. Consider these three packages:<br />
<br />
Package A:<br />
<haskell><br />
module PackageA where<br />
<br />
class Monad m => MonadLogger m<br />
instance MonadLogger IO<br />
</haskell><br />
<br />
Package B, depends on package A:<br />
<haskell><br />
module PackageB where<br />
<br />
import PackageA<br />
<br />
f :: MonadLogger m => Int -> m String<br />
f = return . show<br />
</haskell><br />
<br />
Package C, depends on package B:<br />
<haskell><br />
module Package C where<br />
<br />
import PackageB<br />
<br />
main :: IO ()<br />
main = f 5 >>= print<br />
</haskell><br />
<br />
Now consider this scenario:<br />
<br />
# Package A removes the <hask>IO</hask> instance and gets its major version number bumped, as required by the PVP.<br />
# Package B, which can still work with the old and new version of package A, changes its dependency on package A to allow for both versions. Package B only gets a patch-level bump.<br />
# Package C might or might not compile, depending on which patch-level version of package B is used.<br />
<br />
The PVP could require that package B bumps its major version number as it now (re-)exports one fewer instances. This will however require more frequent version bumps in the whole ecosystem. As a pragmatic solution, for now the PVP doesn't required a major version bump in this case and instead leaves it to package C to add a dependency on package A to handle this situation.<br />
<br />
=== Version tags ===<br />
<br />
The components of the version number must be numbers! Historically Cabal supported version numbers with string tags at the end, e.g. <tt>1.0-beta</tt> This proved not to work well because the ordering for tags was not well defined. Version tags are [https://github.com/haskell/cabal/issues/890 no longer supported] and mostly ignored, however some tools will fail in some circumstances if they encounter them.<br />
<br />
This can sometimes trip you up if you accidentally stumble into using the deprecated tags syntax without realising it, for example a version number with a date like <tt>1.0.2014-01-27</tt> would be interpreted as the version <tt>1.0.2014</tt> with tags <tt>01</tt> and <tt>27</tt>.<br />
<br />
== Dependencies in Cabal ==<br />
<br />
When publishing a Cabal package, you should ensure that your dependencies in the <tt>build-depends</tt> field are accurate. This means specifying not only lower bounds, but also upper bounds on every dependency. <br />
<br />
At some point in the future, Hackage may refuse to accept packages that do not follow this convention. The aim is that before this happens, we will put in place tool support that makes it easier to follow the convention and less painful when dependencies are updated.<br />
<br />
To minimize breakage when new package versions are released, you can use dependencies that are insensitive to minor version changes (e.g. <tt>foo >= 1.2.1 && < 1.3</tt>). However, note that this approach is slightly risky: when a package exports more things than before, there is a chance that your code will fail to compile due to new name-clash errors. The risk from new name clashes may be small, but you are on the safe side if you [[Import modules properly|import identifiers explicitly or using qualification]].<br />
<br />
== Version syntax ==<br />
<br />
Since Cabal 1.6, you can specify an exact API version according to this policy with the special syntax <tt>package == 1.1.4.*</tt> or an API version up to additions with <tt>package == 1.1.*</tt>. The former translates into <tt>package >= 1.1.4 && < 1.1.5</tt>, for example - notice that 1.1.4 ''is'' included, rather than just including 1.1.4.0.<br />
<br />
== Tools ==<br />
<br />
* script to check for API changes in gtk2hs: http://code.haskell.org/gtk2hs/tools/apidiff/<br />
* [http://hackage.haskell.org/package/precis precis] - a simple tool for a first approximation of package API differences, see the [http://www.haskell.org/pipermail/haskell-cafe/2010-April/077023.html announcement]<br />
* {{HackagePackage|id=check-pvp}} is a program that checks for consistency between package dependencies and import style.<br />
<br />
== Related ==<br />
<br />
* [[Sven Moritz Hallberg]], "[[The_Monad.Reader/Issue2/EternalCompatibilityInTheory|Eternal compatibility in theory]]," [[The Monad.Reader]], [[The Monad.Reader/Issue2|Issue 2]]<br />
* [http://semver.org/ Semantic Versioning] is similar, but allows for version tags and defines how tags affect the ordering.</div>Lspitznerhttps://wiki.haskell.org/index.php?title=Debugging&diff=60509Debugging2016-01-11T18:06:24Z<p>Lspitzner: replace deprecated flags</p>
<hr />
<div>== Stack trace ==<br />
<br />
<br />
<br />
=== General usage ===<br />
<br />
Recent versions of GHC allow a dump of a stack trace (of all cost centres) when an exception is raised. In order to enable this, compile with <code>-prof</code>, and run with <code>+RTS -xc</code>. (Since only the cost centre stack will be printed, you may want to add <code>-fprof-auto -fprof-cafs</code><ref name=depflags></ref> to the compilation step to include all definitions in the trace.) Since GHC version 7.8, the function [http://hackage.haskell.org/package/base/docs/GHC-Stack.html#v:errorWithStackTrace errorWithStackTrace] can be used to programmatically dump the stack trace, see [http://www.reddit.com/r/haskell/comments/2fwwx3/how_to_get_approx_stack_traces_with_profiled/ How to get (approx) stack traces with profiled builds].<br />
<br />
A more detailed list of options can be found [http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html#rts-options-debugging in the RTS section] of the GHC user's guide.<br />
<br />
<br />
<br />
=== Example ===<br />
<br />
<haskell><br />
-- test.hs<br />
crash = sum [1,2,3,undefined,5,6,7,8]<br />
main = print crash<br />
</haskell><br />
<br />
<br />
> ghc-7.6.3 test.hs -prof -fprof-auto -fprof-cafs && ./test +RTS -xc<br />
*** Exception (reporting due to +RTS -xc): (THUNK_2_0), stack trace: <br />
GHC.Err.CAF<br />
--> evaluated by: Main.crash,<br />
called from Main.CAF:crash_reH<br />
test: Prelude.undefined<br />
<br />
<br />
== Printf and friends ==<br />
<br />
The simplest approach is to use <tt>Debug.Trace.trace</tt>:<br />
<pre><br />
trace :: String -> a -> a<br />
</pre><br />
: "''When called, trace outputs the string in its first argument, before returning the second argument as its result.'"<br />
<br />
A common idiom to trace a function is:<br />
<pre><br />
myfun a b | trace ("myfun " ++ show a ++ " " ++ show b) False = undefined<br />
myfun a b = ...<br />
</pre><br />
The advantage is that disabling and enabling the trace takes only one line comment.<br />
<br />
You must keep in mind that due to lazy evaluation your traces will only print if the value they wrap is ever demanded.<br />
<br />
The trace function is located in the base package. The package [http://hackage.haskell.org/package/htrace htrace] defines a trace function similar to the one in the base package, but with indentation for better visual effect (see the [http://www.haskell.org/pipermail/haskell-cafe/2012-January/098847.html mailing list thread] for examples). Other tools can be found at [http://hackage.haskell.org/packages/#cat:Debug the debug category in Hackage].<br />
<br />
A more powerful alternative for this approach is [http://hackage.haskell.org/package/hood Hood]. Even if it hasn't been<br />
updated in some time, Hood works perfectly with the current ghc<br />
distribution. Even more, Hugs has it already integrated, see the [http://cvs.haskell.org/Hugs/pages/users_guide/observe.html manual page]. Add an <tt>import Observe</tt> and start inserting observations in your code.<br />
For instance:<br />
<pre><br />
import Hugs.Observe<br />
<br />
f' = observe "Informative name for f" f <br />
f x = if odd x then x*2 else 0<br />
</pre><br />
And then in hugs:<br />
<pre><br />
Main> map f' [1..5]<br />
[2,0,6,0,10]<br />
<br />
>>>>>>> Observations <<<<<<<br />
<br />
Informative name for f<br />
{ \ 5 -> 10<br />
, \ 4 -> 0<br />
, \ 3 -> 6<br />
, \ 2 -> 0<br />
, \ 1 -> 2<br />
}<br />
<br />
</pre><br />
<br />
outputs a report of all the invocations of f and their result.<br />
<br />
I have a handy bogus Hugs.Observe module with no-ops for the observations so that I don't need to remove them manually, expecting that the compiler will optimize them away.<br />
<br />
The [http://hackage.haskell.org/package/GHood GHood] package adds a graphical back-end to Hood. See also the [http://community.haskell.org/~claus/GHood/ GHood homepage].<br />
<br />
<br />
== The Safe Library ==<br />
<br />
There is a safe library of functions from the Prelude that can crash, see [http://community.haskell.org/~ndm/safe/ the safe library]. If you get an error message such as "pattern match failure, head []", you can then use <tt>headNote "extra information"</tt> to get a more detailed error message for that particular call to <tt>head</tt>. The safe library also has functions that return default values and wrap their computation in <tt>Maybe</tt> as required.<br />
<br />
<br />
== Offline analysis of traces ==<br />
The most advanced debugging tools are based in offline analysis of traces.<br />
<br />
=== Haskell Tracer HAT ===<br />
<br />
[http://projects.haskell.org/hat/ Hat] is probably the most advanced tool for this, offering a comprehensive set of tools. [[User:NeilMitchell|Neil Mitchell]] has made available a Windows port of Hat at [http://projects.haskell.org/~ndm/hat/ his site].<br />
<br />
The disadvantage of traditional Haskell tracers is that they either need to transform the whole program or require a specialized run-time system. Therefore they are not always compatible with the latest libraries, so you can put them to use only in some cases. <br />
<br />
=== Hoed - The Lightweight Haskell Tracer and Debugger ===<br />
<br />
[https://github.com/MaartenFaddegon/Hoed Hoed] is a tracer/debugger that offers most of HATs functionality, and works with untransformed libraries. Hoed can therefore be used to debug much more programs than traditional tracer/debuggers.<br />
<br />
To locate a defect with Hoed you annotate suspected functions and compile as usual. Then you run your program, information about the annotated functions is collected. Finally you connect to a debugging session using a webbrowser.<br />
<br />
== Dynamic breakpoints in GHCi ==<br />
<br />
Finally, the [[GHC/GHCi debugger| GHCi debugger]] enables dynamic<br />
breakpoints and intermediate values observation. <br />
<br />
This tool allows to set breakpoints in your code, directly from the GHCi command prompt. An example session:<br />
<pre><br />
*main:Main> :break Main 2<br />
Breakpoint set at (2,15)<br />
*main:Main> qsort [10,9..1]<br />
Local bindings in scope:<br />
x :: a, xs :: [a], left :: [a], right :: [a]<br />
<br />
qsort2.hs:2:15-46> :sprint x<br />
x = _<br />
qsort2.hs:2:15-46> x<br />
</pre><br />
This is an untyped, unevaluated computation. You can use <hask>seq</hask> to force its evaluation and then <code>:print</code> to recover its type<br />
<pre><br />
qsort2.hs:2:15-46> seq x ()<br />
() <br />
qsort2.hs:2:15-46> :p x<br />
x - 10<br />
</pre><br />
<br />
Once a breakpoint is hit, you can explore the bindings in scope, as well as to evaluate any Haskell expression, as you would do in a normal GHCi prompt. The <code>:print</code> command can be very useful to explore the laziness of your code.<br />
<br />
<br />
== Source-located errors ==<br />
<br />
[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/loch LocH] provides wrappers over<br />
<hask>assert</hask> for generating source-located exceptions and errors.<br />
<br />
Consider the use of a located <hask>fromJust</hask>:<br />
<br />
<haskell><br />
import Debug.Trace.Location<br />
import qualified Data.Map as M<br />
import Data.Maybe<br />
<br />
main = do print f<br />
<br />
f = let m = M.fromList<br />
[(1,"1")<br />
,(2,"2")<br />
,(3,"3")]<br />
s = M.lookup 4 m<br />
in fromJustSafe assert s<br />
<br />
fromJustSafe a s = check a (fromJust s)<br />
</haskell><br />
<br />
This will result in:<br />
<br />
<haskell><br />
$ ./a.out<br />
a.out: A.hs:12:20-25: Maybe.fromJust: Nothing<br />
</haskell><br />
<br />
This can be automated, using the 'loch' preprocessor, so a program<br />
failing with:<br />
<br />
<code><br />
$ ghc A.hs --make -no-recomp<br />
[1 of 1] Compiling Main ( A.hs, A.o )<br />
Linking A ...<br />
<br />
$ ./A<br />
A: Maybe.fromJust: Nothing<br />
</code><br />
<br />
Can be transformed to a src-located one by adding:<br />
<br />
<haskell><br />
import Debug.Trace.Location<br />
</haskell><br />
<br />
and then recompiling with the preprocessor on:<br />
<br />
<code><br />
$ ghc A.hs --make -pgmF loch -F -no-recomp<br />
[1 of 1] Compiling Main ( A.hs, A.o )<br />
Linking A ...<br />
<br />
$ ./A<br />
A: A.hs:14:14-19: Maybe.fromJust: Nothing<br />
</code><br />
<br />
<br />
== Other tricks ==<br />
<br />
* If you use GHC, you can get a stack trace in the console when your program fails with an error condition. See the [http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html#rts-options-debugging description of relevant runtime options].<br />
* Some tips how to use GHCi debugger are also in [http://www.haskell.org/pipermail/glasgow-haskell-users/2009-February/016571.html this message].<br />
<br />
<br />
=== Locating a failure in a library function ===<br />
<br />
The simplest way to provide locating in the source code a mismatch<br />
run-time error in the library functions:<br />
<haskell><br />
head, tail, fromJust<br />
</haskell><br />
<br />
and others is to avoid these functions and to use explicit matching instead.<br />
<br />
For example, consider:<br />
<br />
<haskell><br />
g x = h $ fromJust $ f x,<br />
</haskell><br />
<br />
ghc-6.6 often loses the reference to <hask>g</hask>, <hask>f</hask>,<br />
and <hask>h</hask> in its run-time error report, when <hask>f</hask><br />
returns <hask>Nothing</hask>.<br />
<br />
But for the program:<br />
<br />
<haskell><br />
g x = let Just y = f x in h y,<br />
</haskell><br />
<br />
GHC reports:<br />
<br />
<haskell><br />
Main: M1.hs:9:11-22:<br />
Irrefutable pattern failed for pattern Data.Maybe.Just y<br />
</haskell><br />
<br />
Indicating the source of the failure.<br />
<br />
<br />
=== Mysterious parse errors ===<br />
<br />
GHC provides `-ferror-spans`, which will give you the exactly position<br />
of the start and end of an offending statement.<br />
<br />
<br />
=== Infinite loops ===<br />
<br />
On glasgow-haskell-users on 21 Nov 2007, pepe made the following suggestion for detecting the cause infinite loops in GHCi. Assuming the offending function is named `loop`, and takes one argument:<br />
<br />
# enable the flag -fbreak-on-error (`:set -fbreak-on-error` in GHCi)<br />
# run your expression with :trace (`:trace loop 'a'`)<br />
# hit Ctrl-C while your program is stuck in the loop to have the debugger break in the loop<br />
# use :history and :back to find out where the loop is located and why.<br />
<br />
''(For which versions? ghci >= 6.8?)''<br />
<br />
<references><br />
<ref name=depflags>was <code>-auto-all -caf-all</code> in previous ghc versions (now deprecated)</ref><br />
</references><br />
<br />
<br />
[[Category:Tools]]<br />
[[Category:Development tools]]</div>Lspitzner