Showing preview only (429K chars total). Download the full file or copy to clipboard to get everything.
Repository: bitemyapp/learnhaskell
Branch: master
Commit: 76018bdb3ec3
Files: 33
Total size: 414.2 KB
Directory structure:
gitextract_f3yckcep/
├── .gitignore
├── Contributing.md
├── LICENSE
├── Makefile
├── README.md
├── coc.md
├── code_to_learn_from.md
├── dialogues.md
├── guide-de.md
├── guide-el.md
├── guide-es.md
├── guide-fr.md
├── guide-hr.md
├── guide-id.md
├── guide-it.md
├── guide-ja.md
├── guide-ko.md
├── guide-pt.md
├── guide-ro.md
├── guide-ru.md
├── guide-sr.md
├── guide-tl.md
├── guide-tr.md
├── guide-ua.md
├── guide-zh_CN.md
├── guide-zh_tw.md
├── install.md
├── libraries.md
├── rts.md
├── specific_topics-ua.md
├── specific_topics.md
├── tools.md
└── write_haskell_as_fast_as_c.md
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
.cabal-sandbox/
cabal.sandbox.config
================================================
FILE: Contributing.md
================================================
# CONTRIBUTING.md
> Building the pdf requires pandoc.
- Don't hyperlink anything that appears in the table-of-content.
* Reason: Those links get messed up in the final pdf.
- After you're done with your edits, use `make` to build the pdf and
verify that everything looks nice.
## Building pdf files
You can build other pdf version of the guide for languages other than
english. For instance, to build the french version:
make pdf-lang GUIDE_LANG=fr
This will output a `tutorial-fr.pdf` file.
Currently the repository provides a `guide-*.md` file for the following
languages:
Language | Parameter
---------: | -------------
German | `GUIDE_LANG=de`
Greek | `GUIDE_LANG=el`
Spanish | `GUIDE_LANG=es`
French | `GUIDE_LANG=fr`
Italian | `GUIDE_LANG=it`
Portuguese | `GUIDE_LANG=pt`
Turkish | `GUIDE_LANG=tr`
Russian | `GUIDE_LANG=ru`
================================================
FILE: LICENSE
================================================
CC0 1.0 Universal
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator and
subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for the
purpose of contributing to a commons of creative, cultural and scientific
works ("Commons") that the public can reliably and without fear of later
claims of infringement build upon, modify, incorporate in other works, reuse
and redistribute as freely as possible in any form whatsoever and for any
purposes, including without limitation commercial purposes. These owners may
contribute to the Commons to promote the ideal of a free culture and the
further production of creative, cultural and scientific works, or to gain
reputation or greater distribution for their Work in part through the use and
efforts of others.
For these and/or other purposes and motivations, and without any expectation
of additional consideration or compensation, the person associating CC0 with a
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
and publicly distribute the Work under its terms, with knowledge of his or her
Copyright and Related Rights in the Work and the meaning and intended legal
effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not limited
to, the following:
i. the right to reproduce, adapt, distribute, perform, display, communicate,
and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or likeness
depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data in
a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation thereof,
including any amended or successor version of such directive); and
vii. other similar, equivalent or corresponding rights throughout the world
based on applicable law or treaty, and any national implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention of,
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
and Related Rights and associated claims and causes of action, whether now
known or unknown (including existing as well as future claims and causes of
action), in the Work (i) in all territories worldwide, (ii) for the maximum
duration provided by applicable law or treaty (including future time
extensions), (iii) in any current or future medium and for any number of
copies, and (iv) for any purpose whatsoever, including without limitation
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
the Waiver for the benefit of each member of the public at large and to the
detriment of Affirmer's heirs and successors, fully intending that such Waiver
shall not be subject to revocation, rescission, cancellation, termination, or
any other legal or equitable action to disrupt the quiet enjoyment of the Work
by the public as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason be
judged legally invalid or ineffective under applicable law, then the Waiver
shall be preserved to the maximum extent permitted taking into account
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
is so judged Affirmer hereby grants to each affected person a royalty-free,
non transferable, non sublicensable, non exclusive, irrevocable and
unconditional license to exercise Affirmer's Copyright and Related Rights in
the Work (i) in all territories worldwide, (ii) for the maximum duration
provided by applicable law or treaty (including future time extensions), (iii)
in any current or future medium and for any number of copies, and (iv) for any
purpose whatsoever, including without limitation commercial, advertising or
promotional purposes (the "License"). The License shall be deemed effective as
of the date CC0 was applied by Affirmer to the Work. Should any part of the
License for any reason be judged legally invalid or ineffective under
applicable law, such partial invalidity or ineffectiveness shall not
invalidate the remainder of the License, and in such case Affirmer hereby
affirms that he or she will not (i) exercise any of his or her remaining
Copyright and Related Rights in the Work or (ii) assert any associated claims
and causes of action with respect to the Work, in either case contrary to
Affirmer's express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or warranties
of any kind concerning the Work, express, implied, statutory or otherwise,
including without limitation warranties of title, merchantability, fitness
for a particular purpose, non infringement, or the absence of latent or
other defects, accuracy, or the present or absence of errors, whether or not
discoverable, all to the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without limitation
any person's Copyright and Related Rights in the Work. Further, Affirmer
disclaims responsibility for obtaining any necessary consents, permissions
or other rights required for any use of the Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to this
CC0 or use of the Work.
For more information, please see
<http://creativecommons.org/publicdomain/zero/1.0/>
================================================
FILE: Makefile
================================================
PANDOC = pandoc
INPUT = README.md
INPUT_LANG = guide-$(GUIDE_LANG).md
OUTPUT = tutorial.pdf
OUTPUT_LANG = tutorial-$(GUIDE_LANG).pdf
TITLE = -V title=LearnHaskell
AUTHOR = -V author=bitemyapp
FONTSIZE = -V fontsize=12pt
FONTFAMILY = -V fontfamily=sans
MAINFONT= -V mainfont=Georgia
PAGESIZE = -V pagesize=a4paper
GEOMETRY = -V geometry=landscape
VARIABLES = $(GEOMETRY) $(FONTSIZE) $(PAGESIZE) $(TITLE) $(AUTHOR) $(FONTFAMILY) $(MAINFONT)
FLAGS = --normalize --smart --toc --latex-engine=xelatex $(VARIABLES)
pdf: README.md
$(PANDOC) -s $(INPUT) -o $(OUTPUT) $(FLAGS) --column=80
pdf-lang: guide-$(GUIDE_LANG).md
$(PANDOC) -s $(INPUT_LANG) -o $(OUTPUT_LANG) $(FLAGS) --column=80
dialogues: dialogues.md
$(PANDOC) -s dialogues.md -o dialogues.pdf $(FLAGS) --column=80
================================================
FILE: README.md
================================================
# How to learn Haskell
This is a recommended path for learning Haskell based on experience helping others. A list of recommendations from one of the authors of the [Haskell Book.](https://haskellbook.com)
## For non-English speakers
- [Auf Deutsch](guide-de.md)
- [En Español](guide-es.md)
- [En Français](guide-fr.md)
- [Na Hrvatskom](guide-hr.md)
- [Bahasa Indonesia](guide-id.md)
- [In Italiano](guide-it.md)
- [日本語](guide-ja.md)
- [한국어](guide-ko.md)
- [Em Português](guide-pt.md)
- [În Română](guide-ro.md)
- [По-русски](guide-ru.md)
- [Srpski](guide-sr.md)
- [Sa Tagalog](guide-tl.md)
- [Türkçe](guide-tr.md)
- [Українською](guide-ua.md)
- [简体中文](guide-zh_CN.md)
- [繁體中文](guide-zh_tw.md)
#### _Don't sweat the stuff you don't understand immediately_. Keep moving!
## Community
Our IRC channel is `#haskell-beginners` on [Libera Chat](https://libera.chat/).
IRC web client [here](https://web.libera.chat/).
The haskell [mailing lists](https://wiki.haskell.org/Mailing_lists).
### Community Guidelines
See [the community guidelines](coc.md) to understand the conduct that is expected in the IRC channel. You'll get a warning if you're not obviously trolling, but be aware the channel is exclusively for those learning or teaching Haskell.
# Installing Haskell
## Use Stack to get going with Haskell
Get [Stack](https://haskellstack.org) to get GHC installed and to build your projects.
If you don't know anything about Stack and would like an overview, check out this [comprehensive Stack video tutorial](https://www.youtube.com/watch?v=sRonIB8ZStw).
## Also, DO NOT INSTALL HASKELL PLATFORM
Instead of following the instructions on Haskell.org, get Stack.
### Why not platform?
https://mail.haskell.org/pipermail/haskell-community/2015-September/000014.html
# How should I learn Haskell?
The core recommendation is to read the lectures and complete all exercises/homework for the Spring 13 version of cis1940 followed by the FP course. Both are linked below. Everything else can be considered optional and is mentioned so you know where to look.
## Haskell Programming from First Principles.
[@dmvianna](https://github.com/dmvianna) wanted me to let you know that the below are just the _free_ recommended resources. If you're willing to check out a book, we heartily recommend our own [Haskell Book!](https://haskellbook.com) If you can't afford the book for any reasons, please email us using the contact information at [our support page](https://haskellbook.com/support.html).
### Haskell Book subsumes all of the primary resources recommended here
## Yorgey's cis1940 course
> _Do this first_ if aren't getting the Haskell Book, this is the best _free_ introduction to Haskell.
Available [online](https://www.seas.upenn.edu/~cis1940/spring13/lectures.html).
[Brent Yorgey](https://byorgey.wordpress.com)'s course is the best I've found so
far. This course is valuable as it will not only equip you to write basic
Haskell but also help you to understand parser combinators.
The only reason you shouldn't start with cis1940 is if you are not a programmer
or are an inexperienced one. If that's the case, start with
[Thompson's book](https://www.haskellcraft.com/craft3e/Home.html) and transition
to cis1940.
---
## Functional Programming course
> This is the course we recommend doing after Yorgey's cis1940 course
Available on github [here](https://github.com/bitemyapp/fp-course).
This will reinforce and give you experience directly implementing the
abstractions introduced in cis1940, this is practice which is _critical_ to
becoming comfortable with everyday uses of Functor/Applicative/Monad/etc. in
Haskell. Doing cis1940 and then the FP course represents the core
recommendation of my guide and is how we teach everyone Haskell.
---
## Supplementary course after cis1940 and the FP course
> Provides more material on intermediate topics
cs240h is available online:
- [Spring 14](http://www.scs.stanford.edu/14sp-cs240h/)
- [Winter 16](http://www.scs.stanford.edu/16wi-cs240h/)
This is [Bryan O'Sullivan](https://github.com/bos)'s online course from the
class he teaches at Stanford. If you don't know who he is, take a gander at half
the libraries any Haskell application ends up needing and his name is on it. Of
particular note if you've already done the Yorgey course are the modules on
phantom types, information flow control, language extensions, concurrency,
pipes, and lenses.
---
# Resources for specific topics in Haskell
These resources are not vetted or tested with learners as cis1940 and FP course have been, but they're linked in [the topic listing](specific_topics.md) so you have ideas on where to begin. This includes things like intermediate/advanced concepts and subjects like tooling and text editors.
## Dialogues
> Hosted in this repository [here](dialogues.md).
These are actually pretty important and helpful. Look here for deep dives on a
variety of topics.
================================================
FILE: coc.md
================================================
# Code of conduct
[See Chris Done's post on teaching](http://chrisdone.com/posts/teaching)
Be kind and courteous. Being mean or rude scares people off and makes people not want to participate.
Low-effort criticism is for the benefit of the person delivering it, not the person receiving it.
Don't describe things as "easy" or "trivial". You're making people feel terrible for having to work hard for their progress. Slow learners are often the most thorough learners, this is something to celebrate!
No feigning surprise. Don't act surprised when somebody says they don't know something. They'll feel terrible and you've accomplished nothing except to make yourself feel sharp.
No well-actually's. When someone says something that's almost - but not entirely - correct, and you say, "well, actually…" and then give a minor correction. This is especially annoying when the correction has no bearing on the actual conversation. This doesn't mean #haskell-beginners isn't about truth-seeking or that we don't care about being precise. Almost all well-actually's are about grandstanding, not truth-seeking.
No back-seat driving. If you see people working through a problem, you shouldn't intermittently interject advice. Let them work it out unless someone asks for help. Avoiding interruptions is [one of the founding purposes of #haskell-beginners](http://chrisdone.com/posts/teaching).
No subtle -isms. Racism, sexism, homophobia, transphobia, and other kinds of bias are not welcome and will not be tolerated.
---
Guidelines by [the Recurse Center manual](https://www.recurse.com/manual). Thanks for releasing it Recurse Center.
================================================
FILE: code_to_learn_from.md
================================================
# Note!
Code listed isn't necessarily complete or a usable product. The point is that the resource linked is mostly code and code that a beginner with a grasp of the basics could learn something from.
# My stuff
- https://github.com/bitemyapp/bloodhound Elasticsearch, mostly datatypes to describe Elasticsearch's query API and JSON parsing/generation.
- https://github.com/bitemyapp/blacktip Distributed k-ordered unique id service. Directly mimicking Flake which was itself based on Snowflake. Not correct/safe as I'm not using the system's monotonic clock.
# Users that write code people should learn from
- https://github.com/michaelxavier
- https://github.com/nikita-volkov somewhat advanced but pokes some interesting stuff
# File operations
- https://gist.github.com/twopoint718/cac0bbe52fd5f0d3b1be Enumerates files in a directory and organizes them by file extension
- https://gist.github.com/bitemyapp/2311fcbfa152ce0980ed Filewriter example from the Haskell.org wiki I believe
# Web apps
- https://github.com/bitemyapp/shawty-prime This URL shortener written in Scotty is explained in detail in [Haskell Programming](https://haskellbook.com)
- https://github.com/thoughtbot/carnival Yesod app. Sort of an open source clone of Disqus.
# Chat
## IRC bots
- https://wiki.haskell.org/Roll_your_own_IRC_bot
## Slack stuff
### Slack API client
- https://hackage.haskell.org/package/slack-api
### Slack bots
- https://github.com/hlian/linklater library/framework
- https://github.com/twopoint718/spocks-brain example bot/app
## Chat application in Servant + React
- https://github.com/farnoy/chat frontend is coffeescript, but the backend is in Haskell
================================================
FILE: dialogues.md
================================================
# Dialogues from the IRC channel or other places
## Transducers
```
19:31 < edwardk> bitemyapp: a transducer is recognizing that the signature of foldl splits
19:31 < edwardk> :t foldl
19:31 < lambdabot> (b -> a -> b) -> b -> [a] -> b
19:31 < bitemyapp> (b -> a -> b) -> (b -> [a] -> b) ?
19:31 < dfeuer> Splits?
19:31 < edwardk> yes, now replace a and [a] with two things and quantify over the bs
19:31 < edwardk> done
19:32 < monochrom> dfeuer: do you want -O1 or -O2?
19:32 < edwardk> type Transducer x y = forall b. (b -> y -> b) -> (b -> x -> b)
19:32 < edwardk> tada transducer
19:32 < edwardk> they compose like lenses
19:32 < edwardk> nuff said
19:32 < edwardk> now the left and right are 'of the same shape
19:32 < edwardk> :t foldl.foldl
19:32 < lambdabot> (b -> a -> b) -> b -> [[a]] -> b
19:32 < edwardk> :t foldl.foldl.foldl
19:32 < lambdabot> (b -> a -> b) -> b -> [[[a]]] -> b
19:33 < edwardk> yay transducers, next? =)
19:35 < bitemyapp> dfeuer: the last definition Hickey gave of transducers was: "a transducer is just a pre-fused
Kleisli arrows in the list monad"
19:35 < dfeuer> bitemyapp, yeeeeeeeeeeaaaaahhhhhh.
19:35 < bitemyapp> edwardk: ^^ does that definition make sense to you?
19:35 < mauke> I like git
19:35 < bitemyapp> tel added that there was ambient mutable state too.
19:35 < xplat> edwardk: what are some other transducers besides foldl and (flip.foldr.flip) or whatever it was?
19:36 < edwardk> xplat: you can define maps and concatmaps, etc.
19:36 < bitemyapp> I'm not entirely sure what the list monad has to do with it, for example.
19:36 < bitemyapp> since it seems to be about folding.
19:36 < edwardk> xplat: you basically just have to say how you explode 'y' into a bunch of 'b's and fold through it
left to right
19:36 < edwardk> er y into a bunch of x's and fold through them left to right
19:37 < edwardk> (or is it the other way around)
19:37 < bitemyapp> I guess that could be monadic.
19:37 < bitemyapp> sorta?
19:37 < bitemyapp> you're not using join though.
19:37 < xplat> x into a bunch of ys
19:37 < bitemyapp> you'd be mapping an x -> [y] and then reducing with fold.
19:37 < bitemyapp> rather than join.
19:37 < bitemyapp> based on edwardk's casual definition.
19:37 < edwardk> @let type Transducer a b = forall r. (r -> b -> r) -> r -> a -> r
19:37 < lambdabot> Defined.
19:37 < edwardk> :t foldl :: Transducer [a] a
19:37 < lambdabot> (r -> a -> r) -> r -> [a] -> r
19:37 < xplat> bitemyapp: it's 'exploding an x into a sequence of ys' i think that brings in the list monad
19:38 < bitemyapp> xplat: yeah, that's what I meant by "I guess that could be monadic"
19:38 < bitemyapp> xplat: but the thing is, it's not really.
19:38 < bitemyapp> xplat: you just need fmap for that.
19:38 < xplat> i wonder if these things have other shapes like traversals and folds do
19:38 < bitemyapp> xplat: fmap can do x -> [y], you need monad for concatMap - ie: join
19:39 < bitemyapp> xplat: since we're not using the parts that are specific to the list monad (bind/join), it's not
really about the list monadic because the reduction is whatever fold we defined.
19:39 < edwardk> :t (\f g r -> g r . f) :: (a -> b) -> Transducer a b
19:39 < lambdabot> (a -> b) -> (r -> b -> r) -> r -> a -> r
19:39 < bitemyapp> so I'm not totally convinced but I can see why the nested introduction of lists would put
somebody into thinking it was about the list monad.
19:39 < edwardk> :let tmap :: (a -> b) -> Transducer a b; tmap f g r = g r . f
19:39 < edwardk> @let tmap :: (a -> b) -> Transducer a b; tmap f g r = g r . f
19:39 < lambdabot> Defined.
19:39 < Ferdirand> hmm
19:40 < edwardk> :t foldl.tmap succ
19:40 < lambdabot> Enum b1 => (b -> b1 -> b) -> b -> [b1] -> b
19:40 < Ferdirand> so what are the other interesting Transducer types, beyond Transducer a [a] ?
19:40 < xplat> Ferdirand: well, you can use foldl or foldr for any Foldable
19:40 < edwardk> :t (\f g r -> foldl g r . f) :: (a -> [b]) -> Transducer a b
19:40 < lambdabot> (a -> [b]) -> (r -> b -> r) -> r -> a -> r
19:40 < edwardk> there you get a concatMap, etc.
19:41 < edwardk> Ferdirand: work for any Foldable, etc.
19:41 < edwardk> anyways its basically just a crippled left-biased Fold
19:41 < Ferdirand> okay, but for instance, does (Transducer [a] a) corresponds to something meaningful ?
19:42 < edwardk> by biasing left it can't handle infinite cases
19:42 < edwardk> Ferdirand: sure its a function from [a] to basically [a] ;)
19:42 < xplat> so far this all seems like stuff that would work with a Fold too; is there a difference?
19:42 < edwardk> Transducer a b is a -> [b] in disguise
19:42 < edwardk> for a finite case
19:42 < edwardk> xplat: no
19:42 < edwardk> xplat: other than the fact that this version doesn't handle infinite cases
19:42 < xplat> it seems like you could get a transducer from any fold by reading it out into Endo
19:43 < edwardk> yes
19:43 < edwardk> :t foldlOf
19:43 < lambdabot> Getting (Dual (Endo r)) s a -> (r -> a -> r) -> r -> s -> r
19:43 < edwardk> yay transducer
19:43 < edwardk> next =)
19:44 < mauke> http://jlongster.com/Transducers.js--A-JavaScript-Library-for-Transformation-of-Data are these the
same transducers?
19:44 < monochrom> dfeuer: OK, I use -O2, the experiment code is "f x y = quot x y + rem x y" and "g x y = q + r
where (q, r) = quotRem x y". whether Int, Integer, or Integral, f and g are different in GHC
core.
19:44 < edwardk> xplat: transducers themselves aren't terribly brain bending, they are just a use of the same
pattern that lens uses. finding a shape that factors through (->) when something gets quantified
and using (.) and id as the way to compose them
19:45 < edwardk> its nice that they've been rediscovered, but there isn't a lot of magic there
```
## State monad vs. fold
Martin:
Hello all,
many times I see a problem and I say to myself: "there is some state". I then play around with the state monad and often
I don't get anywhere. Then at some point I realizes, that all I need is a simple fold. I don't think I ever used the
state monad outside of toy examples.
Can someone give me some insights when the State Monad is beneficial and where a fold is the better choice.
* * * * *
John Wiegley:
>>>>> martin <martin.drautzburg@web.de> writes:
> Can someone give me some insights when the State Monad is beneficial and
> where a fold is the better choice.
Looking at the type of a fold:
```haskell
foldr :: (a -> b -> b) -> b -> [a] -> b
```
If we juggle the arguments we get:
```haskell
foldr :: (a -> b -> b) -> [a] -> b -> b
```
And if we imagine State b () actions, we can directly rewrite this as:
```haskell
foldrS :: (a -> State b ()) -> [a] -> State b ()
```
Which generalizes to:
```haskell
foldrS :: MonadState b m => (a -> m ()) -> [a] -> m ()
```
Which is roughly the same thing as using mapM_ over our State monad:
```haskell
mapM_ :: Monad m => (a -> m b) -> [a] -> m ()
```
In other words, these two forms in our example say the same thing:
```haskell
foldr f b xs
execState (mapM_ f' xs) b
```
With the only difference being the types of f and f':
```haskell
f : a -> b -> b
f' : a -> State b ()
```
The other question you asked is when to choose one over the other. Since they
are equivalent, it's really up to you. I tend to prefer using a fold over
State, to keep things on the level of functions and values, rather than
pulling in monads and possibly monad transformers unnecessarily.
But it's a very good thing to hold these isomorphisms in your mind, since you
can then freely switch from one representation to another as need be. This is
true of a lot of type equivalences throughout Haskell, where the more things
you can see as being essentially the same, the more freedom you have to find
the best abstraction for a particular context.
## On $ and . operator
```haskell
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther list = reverse .doubleEveryOtherForward . reverse $ list
```
```
03:28 < bitemyapp> fbernier: reverse the list, double every other number, re-reverse the list.
03:28 < bitemyapp> fbernier: the "dot" operator is just function composition.
03:28 < bitemyapp> it's nothing special, just another function.
03:28 < bitemyapp> :t (.)
03:28 < lambdabot> (b -> c) -> (a -> b) -> a -> c
03:30 < bitemyapp> fbernier: the use of $ in that function is a little idiosyncratic and unnecessary, but not problematic.
03:37 < ReinH> fbernier: there's a missing space after the . is all
03:38 < ReinH> fbernier: f x = foo $ x ==> f = foo
03:39 < ReinH> so f x = foo . bar $ x ==> f = foo . bar
03:39 < bitemyapp> fbernier: I think it's just making it point-free in this case.
03:39 < bitemyapp> @pl f x = c . b . a $ x
03:39 < lambdabot> f = c . b . a
03:39 < bitemyapp> yeah, that ^^
03:39 < bitemyapp> fbernier: identical ^^
03:40 < ReinH> fbernier: generally, when you see a $ you can wrap the things on either side with parens and get the same expression:
03:40 < ReinH> f x = foo . bar . bazz $ x ==> f x = (foo . bar . bazz) x
03:40 < ReinH> since (x) = x, ofc
03:41 < bitemyapp> @src ($)
03:41 < lambdabot> f $ x = f x
03:41 < bitemyapp> fbernier: That's the definition of $, only other thing missing is the high precedence set for it.
03:41 < ReinH> the exception is chains of $, like foo $ bar $ baz, where you have to parenthesize in the right direction
03:41 < ReinH> or the left direction, depending on how you look at it
03:42 < bitemyapp> fbernier: http://hackage.haskell.org/package/base-4.7.0.1/docs/Prelude.html ctrl-f for $ to see more
03:42 < bitemyapp> fbernier: infixr 0 is the precedence, highest there is AFAIK
03:42 < bitemyapp> fbernier: the "infixr" means it's right associative
03:42 < bitemyapp> fbernier: as opposed to infixl which would mean left associative
03:43 < ReinH> bitemyapp: or lowest, depending on how you look at it. ;)
03:43 < bitemyapp> foo $ bar $ baz ~ foo (bar (baz))
03:43 < bitemyapp> but if it was infixl
03:43 < bitemyapp> (((foo) bar) baz)
```
## Infix operators as prefix
```
04:12 < ReinH> all infix operators can be written prefix
04:12 < ReinH> with this one weird trick. Other haskellers hate him.
04:13 < bitemyapp> > ($) id 1
04:13 < lambdabot> 1
04:13 < bitemyapp> > id $ 1
04:13 < lambdabot> 1
04:13 < bitemyapp> > id 1
04:13 < lambdabot> 1
```
## Reduction, strict evaluation, ASTs, fold, reduce
```
05:00 < ReinH> pyro-: well, "reduce" already has a typeclass, depending on what you mean
05:00 < ReinH> so does "evaluation", depending on what you mean
05:02 < pyro-> ReinH: reduce is lambda calculus under strict evaluation
05:02 < ReinH> Yep, and it's also the other thing too.
05:02 < ReinH> ;)
05:03 < pyro-> :|
05:03 < pyro-> oh, like on lists?
05:04 < mm_freak_> dealing with ASTs is a real joy in haskell, because most of the code writes itself =)
```
## Continuation passing style, CPS transform
```
05:10 < pyro-> now i am writing a cpsTransform function :D
05:10 < pyro-> it already works, but the current version introduces superflous continuations
05:10 < pyro-> so i am trying to fix :D
05:10 < ReinH> pyro-: Here's a CPS transform function: flip ($)
05:11 < pyro-> i will find out about flip
05:11 < ReinH> @src flip
05:11 < lambdabot> flip f x y = f y x
05:11 < ReinH> pyro-: the essence of CPS can be described as follows:
05:11 < ReinH> :t flip ($)
05:11 < lambdabot> b -> (b -> c) -> c
05:12 < ReinH> is the type of a function which takes a value and produces a suspended computation that takes a continuation and runs it against the value
05:12 < ReinH> for example:
05:12 < ReinH> > let c = flip ($) 3 in c show
05:12 < lambdabot> "3"
05:12 < ReinH> > let c = flip ($) 3 in c succ
05:12 < lambdabot> 4
05:13 < mm_freak_> direct style: f x = 3*x + 1
05:13 < mm_freak_> CPS: f x k = k (3*x + 1)
05:13 < mm_freak_> the rules are: take a continuation argument and be fully polymorphic on the result type
05:13 < mm_freak_> f :: Integer -> (Integer -> r) -> r
05:14 < mm_freak_> as long as your result type is fully polymorphic and doesn't unify with anything else in the type signature you can't do anything wrong other than to descend
into an infinite recursion =)
05:14 < mm_freak_> good: (Integer -> r) -> r
05:15 < mm_freak_> bad: (Integer -> String) -> String
05:15 < mm_freak_> bad: (Num r) => (Integer -> r) -> r
05:15 < mm_freak_> bad: r -> (Integer -> r) -> r
05:15 < pyro-> but flip ($) is not what i had in mind :D
05:16 < mm_freak_> that's just one CPS transform… there are many others =)
05:16 < ReinH> No, it's probably not.
05:16 < ReinH> But other things are pretty much generalizations of that
```
```haskell
type Variable = String
data Expression = Reference Variable
| Lambda Variable Expression
| Combination Expression Expression
type Kvariable = String
data Uatom = Procedure Variable Kvariable Call
| Ureference Variable
data Katom = Continuation Variable Call
| Kreference Variable
| Absorb
data Call = Application Uatom Uatom Katom
| Invocation Katom Uatom
cpsTransform :: Expression -> Katom -> Call
cpsTransform (Reference r) k = Invocation k $ Ureference r
cpsTransform (Lambda p b) k = Invocation k $ Procedure p
"k" $
cpsTransform b $ Kreference "k"
cpsTransform (Combination a b) k = cpsTransform a $ Continuation "v" $ cpsTransform b k
```
### Later...
```
05:38 < ReinH> So for example, if you have an incredibly simple expression language like data Expr a = Val a | Neg a | Add a a
05:38 < ReinH> a (more) initial encoding of an expression would be Add (Val 1) (Neg (Val 1))
05:38 < ReinH> A (more) final encoding might be (1 - 1) or even 0
05:39 < ReinH> The initial encoding generally is more flexible (you can still write a double-negation elimination rule, for instance
05:39 < ReinH> the final encoding is less flexible, but also does more work up-front
05:40 < ReinH> More initial encodings tend to force you to use quantification and type-level tricks, CPS and pre-applied functions tend to appear more in final encodings
05:40 < ReinH> An even smaller example:
05:40 < ReinH> \f z -> foldr f z [1,2,3] is a final encoding of the list [1,2,3]
05:41 < ReinH> pyro-: I'm not really a lisper, but I'm always looking for good reading material
05:41 < ReinH> for bonus points, the foldr encoding is *invertible* as well :)
05:44 < ReinH> pyro-: the relevance is that you seem to be using the cps transform in a more initial encoding than I usually see it
05:44 < ReinH> not that this is at all bad
05:46 < bitemyapp> ReinH: where does the invertibility in the final encoding come from?
05:46 < ReinH> foldr (:) [] :)
05:46 < ReinH> it's not generally so
05:46 < bitemyapp> > foldr (:) [] [1, 2, 3]
05:46 < lambdabot> [1,2,3]
05:47 < bitemyapp> I may not understand the proper meaning of invertibility in this case.
05:47 < bitemyapp> Do you mean invertibility from final to initial encoding?
05:47 < ReinH> Just that, yes
05:47 < bitemyapp> how would it get you back to final from initial?
05:47 < ReinH> I'm not sure if that's the correct term
05:47 < bitemyapp> I don't think it is, but the intent is understood and appreciated.
05:48 < bitemyapp> invertibility implies isomorphism, implies ability to go final -> initial -> final
05:48 < ReinH> well, there is an isomorphism
05:48 < bitemyapp> well, we've established final -> initial, where's initial -> final for this example?
05:49 < bitemyapp> I figured it was a morphism of some sort, but with only a final -> initial and not a way to get back, I wasn't sure which.
05:49 < ReinH> toInitial k = k (:) []; toFinal xs = \f z -> foldr f z xs
05:49 < bitemyapp> thank you :)
```
### Something about adjunctions. I don't know.
```
05:51 < ReinH> bitemyapp: usually one loses information going from initial to final though
05:51 < ReinH> there's probably an adjunction here
05:51 < ReinH> there's always an adjunction
05:52 < ReinH> lol of course there's an adjunction
```
## Data structures with efficient head and tail manipulation
Asker:
I am teaching myself haskell. The first impression is very good.
But phrase "haskell is polynomially reducible" is making me sad :(.
Anyway I am trying to backport my algorithm written in C. The key to
performance is to have ability to remove element from the end of a
list in O(1).
But the original haskell functions last and init are O(n).
My questions are:
1) Is last function is something like "black box" written in C++ which
perform O(1)?
So I shouldn't even try to imagine some haskell O(1) equivalent.
2) Or will optimizer (llvm?) reduce init&last complexity to 1?
3) Some people suggest to use sequences package, but still how do they
implement O(1) init&last sequences equivalent in haskell?
* * * * *
Tom Ellis:
I'm rather confused about your question. If you want a Haskell data
structure that supports O(1) head, tail, init and last why not indeed use
Data.Sequence as has been suggested? As for how it's implemented, it uses
the (very cool) fingertree datastructure. See here for more details:
* * * * *
Asker:
Tom said that finger tree gives us O(1) on removing last element, but
in haskell all data is persistent.
So function should return list as is minus last element. How it could
be O(1)? This is just blows my mind...
My hypothesis is that somehow compiler reduces creating of a new list
to just adding or removing one element. If it is not so.
Then even ':' which is just adding to list head would be an O(n)
operation just because it should return brand new list with one elem
added. Or maybe functional approach uses pretty much different
complexity metric, there copying of some structure "list" for example
is just O(1)? If so then Q about compiler is still exists.
* * * * *
Tom Ellis:
Sounds like magic doesn't it :)
But no, there's no compiler magic, just an amazing datastructure. The
caveat is that the complexity is amortised, not guaranteed for every
operation. Have a look at the paper if you learn about how it works. It's
linked from the Hackage docs.
http://hackage.haskell.org/package/containers-0.2.0.1/docs/Data-Sequence.html
* * * * *
Asker:
Jake It would be great if you give some examples when find your
notebook :) And link to the book about pure functional data structures
which you are talking about.
Also If some "haskell.org" maintainers are here I'd like to recommend
them to pay more attention to optimality/performance questions.
Because almost first question which is apeared in head of standart
C/C++ programmer is "Do I get same perfomance?" (even if he do not
need it).
Maybe some simple and cool PDF tutorial which describes why haskell
could be as fast as others will be great to have.
* * * * *
Richard A. O'Keefe:
> I am teaching myself haskell. The first impression is very good...
> Anyway I am trying to backport my algorithm written in C. The key to
> performance is to have ability to remove element from the end of a
> list in O(1).
You can't. Not in *any* programming language. That's because
lists are one of many possible implementations of the "sequence"
concept, and they are optimised to support some operations at
the expense of others. At the beginning level, you should think
of all Haskell data structures as immutable; fixed; frozen;
forever unchanged. You can't even remove an element from the
front of a Haskell list, at all. All you can do is to forget
about the original list and concentrate on its tail.
> But the original haskell functions last and init are O(n).
Haskell lists are singly linked lists. Even by going to
assembly code, you could not make these operations O(1)
without *using a different data structure*.
> My questions are:
> 1) Is last function is something like "black box" written in C++ which
> perform O(1)?
No.
> 2) Or will optimizer (llvm?) reduce init&last complexity to 1?
No.
> 3) Some people suggest to use sequences package, but still how do they
> implement O(1) init&last sequences equivalent in haskell?
Well, you could try reading Chris Okasaki's functional data
structures book.
There is a classic queue representation devised for Lisp
last century which represents
<a,b,c,d,e>
by ([a,b],[e,d,c])
so that you can push and pop at either end.
When the end you are working on runs out, you
reverse the other end, e.g.,
([],[e,d,c]) -> ([c,d,e],[]).
That can give you a queue with *amortised* constant time.
(There is a technical issue which I'll avoid for now.)
But let's start at the beginning.
You have an interesting problem, P.
You have an algorithm for it, A, written in C.
You want an algorithm for it, H, written in Haskell.
Your idea is to make small local syntactic changes
to A to turn in into H.
That's probably going to fail, because C just
loves to smash things, and Haskell hates to.
Maybe you should be using quite a different approach,
one that would be literally unthinkable in C.
After all, being able to do things that are unthinkable
in C is one of the reasons for learning Haskell.
Why not tell us what problem P is?
* * * * *
Tony Morris:
data SnocList a = SnocList ([a] -> [a])
Inserts to the front and end in O(1).
### I consider the following conclusive
Edward Kmett:
Note: all of the options for playing with lists and queues and fingertrees come with trade-offs.
Finger trees give you O(log n) appends and random access, O(1) cons/uncons/snoc/unsnoc etc. but _cost you_ infinite lists.
Realtime queues give you the O(1) uncons/snoc. There are catenable output restricted deques that can preserve those and can upgrade you to O(1) append, but we've lost unsnoc and random access along the way.
Skew binary random access lists give you O(log n) drop and random access and O(1) cons/uncons, but lose the infinite lists, etc.
Tarjan and Mihaescu's deque may get you back worst-case bounds on more of the, but we still lose O(log n) random access and infinite lists.
Difference lists give you an O(1) append, but alternating between inspection and construction can hit your asymptotics.
Lists are used by default because they cleanly extend to the infinite cases, anything more clever necessarily loses some of that power.
## listen in Writer monad
```
20:26 < ifesdjee_> hey guys, could anyone point me to the place where I could read up on how `listen` of writer monad works?
20:26 < ifesdjee_> can't understand it from type signature, don't really know wether it does what i want..
20:30 < ReinH> :t listen
20:30 < lambdabot> MonadWriter w m => m a -> m (a, w)
20:31 < mm_freak_> ifesdjee_: try this: runWriterT (listen (tell "abc" >> tell "def") >>= liftIO . putStrLn . snd)
20:33 < mm_freak_> in any case 'listen' really just embeds a writer action and gives you access to what it produced
20:33 < ifesdjee_> most likely i misunderstood what happens in `listen`...
20:34 < ifesdjee_> i thought i could access current "state" of writer
20:34 < mm_freak_> remember that the embedded writer's log still becomes part of the overall log
20:34 < mm_freak_> execWriter (listen (tell "abc") >> tell "def") = "abcdef"
20:35 < mm_freak_> all you get is access to that "abc" from within the writer action
20:35 < ifesdjee_> yup, I see
20:35 < ifesdjee_> thank you a lot!
20:35 < mm_freak_> my pleasure
20:37 < mm_freak_> i wonder why there is no evalWriter*
20:37 < ifesdjee_> not sure, really
```
## Introduction and origination of free monads
```
21:32 < sclv> does anyone have a citation for the introduction of free monads?
21:33 < sclv> they’re so universally used in the literature nobody cites where they came from anymore
21:33 < sclv> in a computational context goes back to ’91 at least
21:40 < sclv> found it
21:40 < sclv> coequalizers and free triples, barr, 1970
```
http://link.springer.com/article/10.1007%2FBF01111838#page-1
Note: Seeing a paper on free monoids dating to 1972 by Eduardo J. Dubuc.
## Rank 2 types and type inference
```
03:13 < shachaf> dolio: Do you know what people mean when they say rank-2 types are inferrable?
03:14 < dolio> Not really. I've never taken the time to understand it.
03:16 < dolio> One reading makes no sense, I think. Because rank-2 is sufficient to lack principal types, isn't it?
03:17 < dolio> Or perhaps it isn't....
03:17 < shachaf> Well, you can encode existentials.
03:17 < dolio> Can you?
03:17 < dolio> forall r. (forall a. a -> r) -> r
03:17 < dolio> I guess that's rank-2.
03:18 < shachaf> You can give rank-2 types to expressions like (\x -> x x)
03:18 < shachaf> What type do you pick for x?
03:19 < dolio> forall a. a -> β
03:19 < dolio> Presumably.
03:20 < shachaf> Does β mean something special here?
03:20 < dolio> It's still open.
03:20 < dolio> Greek for unification variables.
03:21 < shachaf> OK, but what type do you infer for the whole thing?03:21 < dolio> forall r. (forall a. a -> r) -> r
03:23 < dolio> (\f -> f 6) : forall r. (Int -> r) -> r
03:23 < dolio> Is that a principal type?
03:23 < shachaf> Do you allow type classes?
03:24 < dolio> People who say rank-2 is decidable certainly shouldn't be thinking about type classes.
03:24 < shachaf> I guess with impredicativity the type you gave works... Well, does it?
03:25 < dolio> Maybe rank-2 is sufficient to eliminate all ambiguities.
03:25 < dolio> Like, one common example is: [id]
03:25 < dolio> Is that forall a. [a -> a] or [forall a. a -> a]
03:25 < dolio> But, we're not talking about Haskell, we're talking about something like system f.
03:26 < dolio> So you'd have to encode.
03:26 < dolio> And: (forall r. ((forall a. a -> a) -> r -> r) -> r -> r) is rank-3.
03:27 < shachaf> I guess...
03:27 < dolio> If I had to guess, that's what the answer is.
```
- Practical type inference for arbitrary-rank types - Peyton Jones, Vytinotis, Weirich, Shields
- https://stackoverflow.com/questions/9259921/haskell-existential-quantification-in-detail
- http://en.wikibooks.org/wiki/Haskell/Polymorphism
## Function types and why a -> b has b^a inhabitants
```
02:17 < bartleby> so I understand sum and product types, but why does a -> b have b^a cardinality?
02:23 < Iceland_jack> How many functions are there of type
02:23 < Iceland_jack> () -> b
02:23 < Iceland_jack> if b has 5 inhabitants?
02:23 < bartleby> 5
02:24 < Iceland_jack> which is 5^1 right?
02:24 < Iceland_jack> You'll want to look at Chris's blog: http://chris-taylor.github.io/blog/2013/02/10/the-algebra-of-algebraic-data-types/
02:24 < bartleby> yes
02:24 < bartleby> purple link, hm... I've been there, might've missed that.
02:25 < Iceland_jack> Now what about
02:25 < Iceland_jack> Bool -> b
02:25 < Iceland_jack> if b has 3 inhabitants
02:25 < Iceland_jack> You can gain your intuition by working these things out for increasingly more involved types
02:26 < bartleby> I was trying this, but it looked like a product type... I'm doing something wrong
02:26 < bartleby> let me see this case
02:26 < Iceland_jack> sure
02:27 < bartleby> wait, if I have one pattern for True and another for False, does it count as a single function? or two?
02:28 < Iceland_jack> If they're two patterns in the same function then it's the same function
02:28 < Iceland_jack> I.e. in the function definition
02:28 < Iceland_jack> f True = ...
02:28 < Iceland_jack> f False = ...
02:28 < Iceland_jack> 'f' is a single function
02:29 < Iceland_jack> and for the first ellipsis '...' you have one of three choices (b = {b1, b2, b3}) and same for the second one
02:29 < pyro-> does b^a include non total functions?
02:29 < Iceland_jack> no
02:29 < pyro-> why is that?
02:30 < Iceland_jack> Because it breaks all sorts of reasoning and makes it more complicated
02:30 < pyro-> :D
02:30 < bartleby> no? I thought that was what I was missing...
02:30 < Iceland_jack> bartleby: How many functions of type
02:30 < Iceland_jack> Bool -> ()
02:31 < bartleby> yes, that's where I'm confused. I'd guess one?
02:31 < Iceland_jack> Right, because the only choice is
02:31 < Iceland_jack> fn True = ()
02:31 < Iceland_jack> fn False = ()
02:31 < bartleby> matching True and False, but only returning ()
02:32 < Iceland_jack> so the number of function |Bool -> ()| is |()| ^ |Bool|
02:32 < Iceland_jack> |()| ^ |Bool|
02:32 < Iceland_jack> = 1 ^ 2
02:32 < Iceland_jack> = 1
02:32 < bartleby> ah, I think I get it
02:33 < Iceland_jack> And there are 2 functions from
02:33 < Iceland_jack> Bool -> ()
02:33 < Iceland_jack> conversely
02:33 < Iceland_jack> oops, () -> Bool I meant
02:33 < pyro-> Just by sitting in this channel I a learning things :D bartleby, how is it that cardinality of a type has interested you? I haven't even heard the term before
02:33 < Iceland_jack> 'const False' and 'const True' respectively
02:33 < bartleby> Iceland_jack: because 2^1
02:33 < Iceland_jack> Precisely
02:34 < Iceland_jack> pyro-: You should definitely read up on the 'Algebra of Algebraic Data Types'
http://chris-taylor.github.io/blog/2013/02/10/the-algebra-of-algebraic-data-types/
02:34 < pyro-> thanks
02:34 < Iceland_jack> Lated parts discuss some more advanced uses
02:34 < Iceland_jack> *Later
02:34 < bartleby> pyro-: Algebraic Data Types, means you have an algebra for dealing with them.
02:35 < Iceland_jack> Just like you knew that
02:35 < Iceland_jack> 1 + 2 = 2 + 1
02:35 < Iceland_jack> in grade school so you can know that
02:35 < Iceland_jack> Either () Bool ≅ Either Bool ()
02:35 < bartleby> blowed my mind when I read about zippers, but I hadn't seen it with functions yet
02:36 < Iceland_jack> viewing (+) = Either, 1 = () and 2 = Bool
02:36 < Iceland_jack> It also means that you can define Bool as
02:36 < Iceland_jack> type Bool = Either () ()
02:36 < Iceland_jack> rather than
02:36 < Iceland_jack> data Bool = False | True
02:36 < Iceland_jack> since
02:36 < Iceland_jack> 1 + 1 ≅ 2
02:37 < Iceland_jack> Given the recent pattern synonyms extensions (PatternSynonyms) you can even use the same constructors and pattern match
02:37 < pyro-> Thats interesting
02:37 < Iceland_jack> type (+) = Either
02:37 < Iceland_jack> type BOOL = () + ()
02:37 < Iceland_jack> pattern TRUE = Right () :: BOOL
02:37 < Iceland_jack> pattern FALSE = Left () :: BOOL
02:38 < Iceland_jack> and then
02:38 < Iceland_jack> not :: BOOL -> BOOL
02:38 < Iceland_jack> not TRUE = FALSE
02:38 < Iceland_jack> not FALSE = TRUE
02:38 < pyro-> what abut values instead of types? 1 + 2 = 2 + 1 works for Int. what about algebra for values of other type?
02:38 < Iceland_jack> pyro-: You're not actually using numbers
02:38 < Iceland_jack> 1 is just a nice and confusing way to refer to the type ()
02:38 < pyro-> i understand
02:38 < bartleby> whoa, easy there boy! I'm overheating with 2^2 here
02:38 < Iceland_jack> not the value 1
02:38 < bartleby> :-D
02:38 < pyro-> thanks
02:39 < Iceland_jack> bartleby: Slowing down :)
02:39 < pyro-> actually that i'm not using numbers is kind of the point right?
02:39 < Iceland_jack> well it makes the analogy with elementary arithmetic clearer
02:39 < bartleby> pyro-: you are counting possible values of that type
02:40 < Iceland_jack> So you can write '2' for Bool because Bool has two things
02:40 < bartleby> so Either () Bool has three because: Left (), or Right True, or Right False
02:40 < Iceland_jack> Maybe Bool would be 3
02:40 < Iceland_jack> Yes exactly
02:40 < Iceland_jack> and thus
02:40 < Iceland_jack> Either () Bool ≅ Maybe Bool
02:41 < Iceland_jack> and also
02:41 < Iceland_jack> Maybe a ≅ Either () a
02:41 < Iceland_jack> If you define
02:41 < Iceland_jack> Maybe b = 1 + b
02:41 < Iceland_jack> Either a b = a + b
02:41 < Iceland_jack> then it becomes fairly clear
02:44 < bartleby> ah, I think it clicked here. I managed to list Bool -> Bool, four different functions
02:46 < Iceland_jack> and then for Bool -> Three where |Three| = 3 you have 3 independent choices for True and False so you have 3 * 3 = 3^2
02:46 < Iceland_jack> and so forth
02:46 < Iceland_jack> hope this clears things up a bit
02:46 < bartleby> I was unsure about partial fuctions, but now it makes sense. It's just a permutations of b I think (not sure if permutation is the right word)
02:47 < bartleby> how many arrangements with `a` elements of type `b` can I make?
02:51 < bartleby> Iceland_jack: thank you. I see that I have that page bookmarked, but I think I didn't get that Functions sections at the time
02:52 < bartleby> in fact, it's still confusing...
02:52 < bartleby> "Then each of First, Second and Third can map to two possible values, and in total there are 2⋅2⋅2 = 2^3 = 8 functions of type Trio -> Bool"
02:53 < bartleby> counting like this I was only seeing First->True, First->False, Second->True, Second->False... 6, like a product
02:54 < Iceland_jack> You have to map all the values
02:54 < Iceland_jack> so the first function might be
02:54 < Iceland_jack> f1 First = False
02:54 < Iceland_jack> f1 Second = False
02:54 < Iceland_jack> f1 Third = False
02:54 < Iceland_jack> And the second function might be
02:54 < Iceland_jack> f2 First = True
02:54 < Iceland_jack> f2 Second = False
02:54 < Iceland_jack> f2 Third = False
02:54 < bartleby> yeah, I missed that. Thinking about combinations is easier IMO. True True True, True True False, ...
02:55 < bartleby> reminds me of truth tables :)
02:55 < Iceland_jack> writing False as 0 and True as 1 you get
02:55 < Iceland_jack> Trio -> Bool = { 000, 001, 010, 011, 100, 101, 110, 111 }
02:55 < Iceland_jack> with
02:55 < Iceland_jack> |Trio -> Bool|
02:56 < Iceland_jack> = |Bool| ^ |Trio|
02:56 < dibblego> a function of the type X -> Y has Y^X possibilites
02:56 < Iceland_jack> = 2 ^ 3 = 8
02:56 < Iceland_jack> right :)
02:57 < Iceland_jack> so a function from
02:57 < Iceland_jack> Trio -> Bool
02:57 < Iceland_jack> has the following implementations
02:57 < Iceland_jack> > replicateM 3 [0, 1]
02:57 < lambdabot> [[0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]
02:58 < Iceland_jack> and
02:58 < Iceland_jack> Quad -> Bool
02:58 < Iceland_jack> > replicateM 4 [0, 1] -- etc.
02:58 < lambdabot> [[0,0,0,0],[0,0,0,1],[0,0,1,0],[0,0,1,1],[0,1,0,0],[0,1,0,1],[0,1,1,0],[0,1,...
02:58 < Iceland_jack> > [ length (replicateM domainSize [0,1]) | domainSize <- [0..6] ]
02:58 < lambdabot> [1,2,4,8,16,32,64]
02:59 < Iceland_jack> > [ 2^domainSize | domainSize <- [0..6] ]
02:59 < lambdabot> [1,2,4,8,16,32,64]
03:01 < bartleby> > replicateM 2 [0,1,2]
03:01 < lambdabot> [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]
03:01 < bartleby> so that's Bool -> Trio. nice
03:01 < Iceland_jack> Which has 3^2 = 9 elements not to put too fine a point on it
03:02 * bartleby is counting subarrays
03:02 < bartleby> yup, nine
03:02 < bartleby> now it makes sense, thanks
03:04 < spion> so basically, you want the number of the possible tables, rather than the number of items in a table?
03:04 < spion> :)
03:04 < dibblego> this is why you find there are 4 implementations of (Bool -> Bool)
03:05 < Iceland_jack> yes since you can interpret each table as a function definition
03:05 < Iceland_jack> True | False
03:05 < Iceland_jack> -----+------
03:05 < Iceland_jack> a | b
03:05 < spion> right
03:05 < Iceland_jack> and
03:05 < Iceland_jack> replicateM (length xs) xs
03:05 < Iceland_jack> should always have n^n elements given n = length xs
03:06 < Iceland_jack> can also be rewritten as
03:06 < Iceland_jack> (length >>= replicateM) xs
03:07 < Iceland_jack> > map (length . (length>>=replicateM) . flip replicate ()) [0..7]
03:07 < lambdabot> [1,1,4,27,256,3125,46656,823543]
03:07 < Iceland_jack> > [ n^n | n <- [0..7] ]
03:07 < lambdabot> [1,1,4,27,256,3125,46656,823543]
```
## Applicative and liftA2
```
02:42 < dibblego> > liftA2 (+) [1,2,3] [30,40,50]
02:42 < lambdabot> [31,41,51,32,42,52,33,43,53]
02:42 < blueclaude> Thanks dibblego
02:42 < dibblego> ! [1+30,1+40,1+50,2+30,2+40,2+50,3+30,3+40,3+50]
02:43 < benzrf> blueclaude: (<*>) on the list applicative is cartesian
product, but applying the first item to the second
02:43 < benzrf> > [(++"foo"), (++"bar")] <*> ["test", "othertest", "more"]
02:43 < lambdabot>
["testfoo","othertestfoo","morefoo","testbar","othertestbar","morebar"]
02:44 < dibblego> > join (Just (Just 4))
02:44 < lambdabot> Just 4
02:44 < dibblego> > join (Just Nothing)
02:44 < lambdabot> Nothing
02:44 < benzrf> > join []
02:45 < lambdabot> []
02:45 < damncabbage> > [(+ 1), (+ 2)] <*> [1,2,3]
02:45 < lambdabot> [2,3,4,3,4,5]
02:45 < dibblego> Maybe is cosemimonad, but not a comonad
02:47 < dibblego> bitemyapp: [] is also cosemimonad but not comonad
```
```haskell
liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c
(<*>) :: Applicative f => f (a -> b) -> f a -> f b
-- by itself, cosemimonad
class Functor w =>
extend :: (w a -> b) -> w a -> w b
```
## RankNTypes with CPS'y example
```haskell
myFunc :: (forall a. a -> (a -> a) -> a) -> Int
myFunc f = f 0 (+1)
-- won't work
-- otherFunc :: (a -> (a -> a) -> a) -> Int
-- otherFunc f = f 0 (+1)
-- use:
-- myFunc (flip ($))
```
```
22:42 < mm_freak_> because 'f' is polymorphic, myFunc gets to apply it
to its own choice of types
22:42 < mm_freak_> in particular it can make different choices in
different places
22:43 < mm_freak_> the "forall" really just means that the function
implicitly takes a type argument
22:44 < bitemyapp> mm_freak_: I think part of the problem is the difference between
22:44 < bitemyapp> (forall a. a -> (a -> a) -> a) -> Int
22:44 < bitemyapp> vs.
22:44 < bitemyapp> forall a. (a -> (a -> a) -> a) -> Int
22:44 < bitemyapp> yes?
22:44 < bitemyapp> the latter being implicitly the case in Haskell.
22:44 < mm_freak_> yes, but think about it… think really really simple in this case
22:45 < mm_freak_> in the former case myFunc receives a polymorphic function, so myFunc
gets to choose the type
22:45 < mm_freak_> in the latter case myFunc itself is polymorphic, so the applier of
myFunc gets to choose it
22:45 < mm_freak_> notice that in the former case myFunc is
monomorphic!
22:46 < mm_freak_> yeah… its type isn't quantified over any type
variables
22:46 < bitemyapp> mm_freak_: but the lambda passed to it is?
22:46 < mm_freak_> yeah
22:46 < bitemyapp> okay, yes.
22:46 < bitemyapp> so we're assigning/shifting around polymorphism
22:46 < bitemyapp> between the top level function the func arg
22:46 < bitemyapp> based on the ranks/nesting
22:46 < bitemyapp> / scope'ish
```
## Functor, algebras, Coyoneda
* * * * *
bitemyapp edited 4 days ago | link | delete | reply
I realize this is partly because the examples are in Scala, but none
of this gets at what a Functor really is.
Functor is an algebra.
Functor is an algebra with one operation, usually called map.
That one operation has a type something like:
```haskell
(a -> b) -> f a -> f b
```
That one operation should respect identity:
```
map id = id
```
And that one operation should be distributive with respect to function composition:
```
map (p . q) = (map p) . (map q)
```
That’s it people. That’s it. Functor is a very weak structure. Many
things can be functor. Many of those things will not look anything
like a “list”, “collection”, or even a “data structure”.
Understanding free objects, free versions of these algebraic
structures, can lend a more faithful intuition for what these things
are.
Glancing at Coyoneda (the free functor) should give one some idea of
why you’re not dealing with something that has anything to do with
lists.
Want to know more?
You know the drill: https://github.com/bitemyapp/learnhaskell
Edit:
Since I take great satisfaction in excising misunderstandings, I’m
going to include a Functor instance that should help drop the
“collections” oriented view of what they are.
```haskell
-- (->) or -> is the type constructor for functions
-- a -> a, the identity function's type is a type of
-- -> taking two parameters of the same type (a and a)
-- (->) a a analogous to Either a b
instance Functor ((->) r) where
map = (.)
-- (.) or . is function composition
-- (.) :: (b -> c) -> (a -> b) -> a -> c
-- more on this Functor instance:
-- https://stackoverflow.com/questions/10294272/confused-about-function-as-instance-of-functor-in-haskell
```
Bonus round for upvoting me:
http://www.haskellforall.com/2012/09/the-functor-design-pattern.html
http://hackage.haskell.org/package/kan-extensions-3.7/docs/Data-Functor-Coyoneda.html
http://oleksandrmanzyuk.wordpress.com/2013/01/18/co-yoneda-lemma/
https://www.reddit.com/r/haskell/comments/17a33g/free_functors_the_reason_free_and_operational_are/c83p8k2
https://gist.github.com/thoughtpolice/5843762
* * * * *
tel 4 days ago | link | reply
```
Understanding free objects, free versions of these algebraic
structures, can lend a more faithful intuition for what these things
are.
```
This is a super great point—it also, meaningfully, applies to other
structures like Monads, Applicatives, or Monoids, Categories,
Arrows. Really quickly, here’s Yoneda and Coyoneda (the “two” free
functors)
```haskell
newtype Yoneda f a = Yoneda { runYoneda :: forall b . (a -> b) -> f b }
data Coyoneda f b where Coyoneda :: f a -> (a -> b) -> Coyoneda f b
```
In each case we see that functor tends to mean having a parametric
structure (the f) and a method of transforming the parameter to
something else (the functions a -> b). When we “collapse” this free
view of a functor we get to decide if, how, when, and why we combine
that structure and its mapping function. For lists we, well, map
it. For something like
```haskell
data Liar a = Liar -- note that `a` does not appear on the right side
```
we just throw the mapping function away.
(Another key point that’s a bit harder to see is that if you map the
Yoneda/Coyoneda formulation repeatedly it does not store each and
every mapping function but instead composes them all together and
retains only that composition. This ensures that functors cannot “see”
how many times fmap has been called. That would let you violate the
functor laws!)
* * * * *
gclaramunt 3 days ago | link | reply
Do you have any reference of functor being an algebra? I’m intrigued
Since we’re clarifying what a functor is, I guess is worth noting that
you’re talking about endofunctors in the (idealized) Hask category. In
category theory, a functor is defined by two mappings: one for objects
in the category and one for arrows, that must preserve identity and
composition (the laws you mention). Since the mapping of objects is
already given by the type constructor, here one needs to provide only
the mapping of functions but it kind of irks me when ppl. say a
functor is only defined by “map” :)
* * * * *
tel 2 days ago | link | reply
Functor is definitely an algebra. Its rules mean that it has tight
relation to certain functors in CT.
* * * * *
gclaramunt edited 2 days ago | link | reply
Interesting… any refereces I can read? Or you’re talking about
F-algebras?
* * * * *
tel 2 days ago | link | reply
I mean “algebra” as “set of operations and equalities”.
* * * * *
gclaramunt 2 days ago | link | reply
Ok. To be honest, I need to familiarize myself with the definition of
algebra, is just that I had never heard this before :)
* * * * *
tel 1 day ago | link | reply
It’s an incredibly overloaded term, tbh. In the context of abstract
algebra you’d probably want to think of a (G, L)-algebra as a set
inductively defined by generators G and laws L. For instance, here’s a
“free” monoid algebra (note that this isn’t a free monoid, but a “free
monoid algebra” or a “free algebra of the monoid type” or a “(monoid,
{})-algebra” maybe)
```haskell
data FMonoid where
Fmempty :: FMonoid
Fmappend :: FMonoid -> FMonoid -> FMonoid
class Monoid FMonoid where -- this is wrong! doesn't follow laws!
mempty = Fmempty
mappend = Fmappend
```
note that it has all the “generators” of the typeclass Monoid but
follows none of the rules (mempty <> mempty != mempty). Typically we
also want to add a set of constants to form the smallest free algebra
over a set
```haskell
data FMonoid a where
Embed :: a -> FMonoid a
Fmempty :: FMonoid a
Fmappend :: FMonoid a -> FMonoid a -> FMonoid a
```
* * * * *
gclaramunt 1 day ago | link | reply
Really interesting, thanks a lot! Now I’m trying to see how this ties
to the Functor typeclass: G are the instance constructors and the
functor laws make L ? I think I’m missing an important piece of the
puzzle here :)
* * * * *
tel 1 day ago | link | reply
You’re not, that’s basically it.
```haskell
data FFunctor f a where
EmbedFunctor :: f a -> FFunctor f a
Ffmap :: (a -> b) -> FFunctor f a -> FFunctor f b
```
This lets you build the free (Functor, {})-algebra over some initial
type f. If we translate it naively then it doesn’t follow the laws
```haskell
class Functor (FFunctor f) where -- wrong!
fmap = Ffmap
```
but we can implement it properly if we’re a little more clever
```haskell
class Functor (FFunctor f) where
fmap f x = case x of
EmbedFunctor fa -> Ffmap f x
Ffmap g fa -> Ffmap (f . g) fa
```
We need one more function, though, since we can’t use EmbedFunctor
directly without exposing information about whether or not we’ve ever
fmaped this functor (which shouldn’t be possible to access, that’s
what fmap id = id says)
```haskell
embed :: f a -> FFunctor f a
embed fa = Ffmap id (EmbedFunctor fa)
```
And now, if we think about it, we can see that every value of FFunctor
constructed using embed and fmap is of the form
```haskell
Ffmap fun (EmbedFunctor fa)
```
And so that EmbedFunctor constructor is totally superfluous. Let’s
remove it
```haskell
data FFunctor f a where
Ffmap :: (a -> b) -> f a -> FFunctor f b
embed :: f a -> FFunctor f a
embed fa = Ffmap id fa
```
And—well—this is just CoYoneda again!
```haskell
lower :: Functor f => FFunctor f a -> f a
lower (Ffmap f fa) = fmap f fa
```
* * * * *
gclaramunt about 9 hours ago | link | reply
Nice Haven’t digested it properly but I see the trick is to capture
the functor with a datatype (is the same thing with free monads,
right?) Now is easier to see from where CoYoneda comes, thanks! (you
did show me an important piece of the puzzle :P )
## Magma, parallelism, free monoid
- [Original post](https://www.fpcomplete.com/user/bss/magma-tree)
- [Guy Steele talk referenced](https://vimeo.com/6624203)
- [Comment thread](https://www.reddit.com/r/haskell/comments/2corq6/algebraic_terraforming_trees_from_magma/)
* * * * *
edwardkmett 7 points an hour ago
Much of Guy Steele's work here pertained to a desire to be able to parallelize calculation. This is a laudable goal.
The main issue with a naïve magma approach Steele proposed for Fortress is that you have zero guarantees about efficient splittability. All the mass of your magma could be on one side or the other.
The benefit is that without those guarantees infinite magmas make sense in a lazy language. You can have infinitely large trees just fine, that go off to infinity at any point not just at the right.
This has a certain pleasing structure to it. Why? Well, lists aren't really the free monoid if you allow for infinitely recursive use of your monoid! You have unit and associativity laws and by induction you can apply them a finite number of times, but reassociating an infinite tree from the left to the right requires an infinite number of steps, taking us out of the constructive world we can program. So ultimately a free Monoid (allowing for infinite monoids) is something like Sjoerd Visscher's
```haskell
newtype Free p = Free { runFree :: forall r. p r => (a -> r) -> r }
type List = Free Monoid
```
Here we borrow the assumption of unit and association from the target r and generate something using it. It is an almost vacuous but now correct construction, whereas the association to the right to make a list required us to be able to right associate infinite trees. You can view this as a sort of quotient on a magma, where you guarantee to only consume it with monoidal reductions.
Binding/substituting on a (unital) magma can now take longer than O(n), why? Because now I have to walk past all the structure. You can replace this with Oleg and Atze's "Reflection without Remorse", but walking down a unital Magma structure doesn't decrease n necesssarily.
In the absence of infinite trees, you usually want some form of balance depending on what you want to do with the structure. e.g. turning it into a catenable deque gives you efficient access to both ends and lets you still glue in O(1) or O(log n).
Switching to a finger tree gives you guaranteed O(log n) splits, but now merges go from O(1) to O(log n)
In a general magma the split is potentially completely lopsided. You can 'steal work' but as often as not you likely steal a single unit, or in a unital magma, possibly nothing.
The cost of these richer structures is you lose the continuous extension to the infinite case, but when trading O(n) or worse for O(log n) it is often worth making that trade-off.
## Why non-strictness (laziness) needs to be the default
```
23:20 < slack1256> It is folklore that lazy evaluation compose better, usually showing how it supports separated
generators/consumers as in "Why functional programming matters", but does this notion of
composition goes further?
23:20 < Cale> slack1256: In what sense?
23:21 < slack1256> as in, if some function is not based on generator/consumer based can still benefit from
laziness?.
23:21 < slack1256> (this is a problem of me having lack of imagination)
23:22 < Cale> slack1256: Most functions are consuming or generating something. Those which produce or consume
larger structures with many parts that could be evaluated separately tend to benefit from laziness.
23:22 < tabemann> from what I gather, though, lazy lists aren't as useful as that paper purported
23:23 < Cale> We use them all the time
23:23 < haasn> Laziness can play well into parallelism
23:23 < haasn> Or, rather, nonstrictness
23:23 < haasn> Only evaluate the strict parts immediately, evaluate parts that don't have to be forced yet in parallel
23:23 < tabemann> what I mean is that there are better lazy sequence data structures than the list
23:23 < Cale> Oh?
23:23 < Cale> Lists are absolutely perfect for what they are
23:24 < slack1256> Mmm you're right, most functions are consuming or generating something, specially in a pure
language.
23:24 < Cale> If you plan on iterating through a list of things in order, then lists present you with about as
concise a representation as possible.
23:24 < Cale> slack1256: Lists are essentially our loops
23:25 < Cale> and it helps sometimes that they can be infinite, or combinatorially large
23:25 < Cale> for the same reason that you might want to have an infinite loop, or one which potentially iterates
more times than you'll practically ever want to actually have the loop body occur.
23:26 < slack1256> In "more points for lazy evaluation" augustss shows that laziness enable efficient higher-order
functions, and bob concedes that point that in strict languages that really hurts because you
have to use manual recursion.
23:26 < Cale> yep
23:26 < slack1256> Maybe I should really learn SML to appreciate more the benefits of laziness
23:27 < josephle> then you'll lament the lack of backpack in Haskell ;)
23:28 < Cale> It really needs to be the default for that reason: if the default is to be strict, when you find the
functions that you want to compose in your library, the chances are good that whoever wrote it won't
have thought about your use case, and you'll need to rewrite it to be explicitly lazy, which defeats
a lot of the point of having things be compositional.
23:31 < Cale> Whereas strictness is just slightly more rarely required, and tends to be the kind of thing that you
can't ignore when you really need it, because your program's performance will suffer dramatically. So
it just becomes a matter of learning to spot the places where it'll be important. The rule of thumb I
use is this: if you're collapsing many individual bits of data down into a single thing which depends
on all of them
23:31 < Cale> and can't be partially evaluated, that's where you want some sort of strict higher-order function
like foldl' or some explicit strictness annotations.
23:32 < Cale> Basically, things you'd think of as accumulations of some sort. You want to avoid building up large
expressions in memory composed of strict functions (functions that must pattern match on their input
to produce any part of their result).
23:34 < Cale> So for instance, when you're repeatedly updating the contents of an IORef, or recursively updating an
accumulating parameter without matching on it, you want to be careful there.
```
## Functor for Reader
```
< OscarZ> instance Functor ((->) t) where
< ajcoppa> OscarZ: you know about (->) from the types of functions, right?
< OscarZ> ajcoppa: yes
< ajcoppa> ((->) t) is a partial definition that describes a function that takes in a value of type t
< OscarZ> ajcoppa: im a bit confused.. so does "instance Functor ((->) t) where" mean that were defining that any function that takes a parameter is a Functor instance?
< ajcoppa> OscarZ: yep!
< OscarZ> ajcoppa: is that different than saying instance Functor (a -> b) where ?
< ajcoppa> OscarZ: it is different, because functors need to have a kind of * -> *
< ajcoppa> as an example, when defining a functor for Optional, you don't say instance Functor (Optional Int) where -- you say instance Functor Optional where
< pjdelport> OscarZ: "Functor ((->) r)" is a lot like "Functor (Either a)" and "Functor ((,) a)"
< pjdelport> OscarZ: You're declaring an instance for a partially-applied type, which itself will get applied to a remaining type (which is the "slot" that the functor operates on)
< pjdelport> OscarZ: So in the same sense that "instance Functor Maybe where ..." means: fmap :: (a -> b) -> Maybe a -> Maybe b
< pjdelport> "instance Functor ((,) x) where ..." means: fmap (a -> b) -> (x,a) -> (x,b)
< pjdelport> Or in equivalent syntax: fmap :: (a -> b) -> ((,) x) a -> ((,) x) b
< pjdelport> where ((,) x) is what "f" gets replaced with
< pjdelport> So for "instance Functor (Either x) where ...", you have fmap :: (a -> b) -> Either x a -> Either x b
< pjdelport> and for "instance Functor ((->) r) where ...", you have fmap :: (a -> b) -> (->) r a -> (->) r b
< pjdelport> or equivalently: fmap :: (a -> b) -> (r -> a) -> (r -> b)
< OscarZ> oh.. i think i finally get it
< pjdelport> OscarZ: To read that more intuitively, just remember what the "slot" that fmap operates on is for each Functor instance: for lists, the "slots" are all of a list's elements. For Maybe, the "slots" are Just values (if any). For Either, the "slots" are Right values.
< pjdelport> OscarZ: For functions, (->), the "slot" that you're operating on is the *result* of the function.
< pjdelport> So applying "fmap f" to a function value like (r -> a) uses f to "replace" the result value 'a' with a 'b', yielding a new function (r -> b).
< pjdelport> (Just like how applying "fmap f" to a list value [a] uses f to "replace" each element 'a' with a 'b', yielding a new list [b].)
< OscarZ> to implement Functor functions with signature a -> a -> a, should it be instance Function ((->) r t) where ?
< pjdelport> OscarZ: a -> a -> a, or (a -> (a -> a)), is just a special case of (a -> b) where b = (a -> a)
< OscarZ> pjdelport: so like Functor (Either a) matches (Either a) part in Either a b, Functor ((->) r) matches just the first a in a -> (a -> a) ? in this case the slot would be of type (a -> a) ?
< pjdelport> OscarZ: Yep.
< OscarZ> ok thanks.. i think i get.. apparently im not used to functions as first-class citizens :) somehow got confused when it was a function instead of something like Either a b
< ajcoppa> it is very normal to need some time to wrap your head around this instance in particular
< pjdelport> Yeah, it can be mind-bending. :)
< pjdelport> but it's good exercise
< OscarZ> you guys are good at explaining :)
< OscarZ> you could teach FP to a rotten cabbage
```
```haskell
-- n.b. * means we're showing kind signatures, not type signatures.
-- application of type arguments
data (->) a b
(->) :: * -> * -> *
((->) e) :: * -> *
instance Functor ((->) r) where
fmap = (.)
instance Functor ((->) r) where
fmap f g = (\x -> f (g x))
data (,) a b = (,) a b
(,) :: * -> * -> *
((,) a) :: * -> *
instance Functor ((,) a) where
fmap f (x,y) = (x, f y)
newtype Reader r a = Reader { runReader :: r -> a }
Reader :: * -> * -> *
(Reader r) :: * -> *
instance Functor (Reader r) where
fmap f m = Reader $ \r -> f (runReader m r)
instance Monad (Reader r) where
return a = R $ \_ -> a
m >>= k = R $ \r -> runReader (k (runReader m r)) r
class Functor (f :: * -> *) where
fmap :: Functor f => (a -> b) -> f a -> f b
class Monad (m :: * -> *) where
(>>=) :: m a -> (a -> m b) -> m b
return :: a -> m a
```
## Join for Reader
```
18:51 < OscarZ> about join... im wondering about join (+) 7 = 14
19:14 < pjdelport> OscarZ: join for Reader becomes even more Intuitive when you
pronounce Reader e a as "function from an environment e to a"
19:15 < pjdelport> Then "Reader e (Reader e a)" is just "function from an environment e
to function from an environment e to a"
19:16 < pjdelport> And joining means turning that into just one "function from an
environment e to a"
19:16 < pjdelport> And saying it like that should (hopefully) make the implementation and what
it does more obvious :)
19:23 < pjdelport> I still think just pondering "type Reader e a = e -> a" is a great way to
to get that "a ha" moment
```
```haskell
λ> join (+) 7
14
λ> join (*) 7
49
```
## Reversing a list operation that uses >>=
SpacemanInBikini:
I made a function in Haskell that takes in a number and returns a list of integers from 1 to that number.
```haskell
gen x = [1..x]
gen 4
-> [1, 2, 3, 4]
```
As I was learning about the monads I noticed that I could bind a list into this function as it has the type of (a -> m a).
```haskell
[2, 3, 6, 1, 4] >>= gen
-> [1, 2, 1, 2, 3, 1, 2, 3, 4, 5, 6, 1, 1, 2, 3, 4]
```
Then I wanted to write a function that would reverse the (>>= gen) and i came up with this function.
```haskell
revgen (x:xs) =
case (null xs) of
False -> case ((head xs) - x) of
1 -> 1 + revgen xs
otherwise -> 0 : revgen xs
True -> 1 : []
```
But it doesn't work, I think because of the revgen returning both numbers and lists. But I can't come up with a way to do this any other way with one function. Also the nested cases look ugly as hell but I quess they work as intented because at least it compiles.
* * * * *
meditans:
Given the definitions:
```haskell
gen x = [1..x]
f xs = xs >>= gen
```
If you want a function g such that g . f = id, I think you could use:
```haskell
g xs = map last $ groupBy (<) xs
```
```haskell
λ> groupBy (<) [1, 2, 1, 2, 3, 1, 2, 3, 4, 5, 6, 1, 1, 2, 3, 4]
[[1,2],[1,2,3],[1,2,3,4,5,6],[1],[1,2,3,4]]
λ> map last $ groupBy (<) [1, 2, 1, 2, 3, 1, 2, 3, 4, 5, 6, 1, 1, 2, 3, 4]
[2,3,6,1,4]
```
## Programmatically finding the inverse of a bijective function
tel:
If the range is finite and the domain has decidable equality
```haskell
class Finite a where
-- x :: a iff elem x universe = True
universe :: [a]
inv :: (Eq b, Finite a) => (a -> b) -> (b -> a)
inv f b = let [a] = [ a | a <- universe, f a == b ] in a
```
The pattern matching above will fail if f is not bijective.
## pseq, seq, sparks
```
16:24 < Lindrian> sparks in haskell seem so... unintuitive
16:24 < Lindrian> It doesnt really follow the traditional sense of how you use threads,
which might be why I find it odd
16:25 < qu1j0t3> this might also be a very good thing :-)
16:26 < Lindrian> why?
16:28 < Lindrian> I need to remember the functionality of seq, par and pseq.
16:28 < Lindrian> seq forces evaluation of the first argument, before returning the second?
par creates a "spark" that allows the first argument to be evaluated at
the same time the second is being returned?
16:28 < Lindrian> I thinkkkkk
16:30 < Lindrian> damn cant remember pseq, gotta look it up
16:31 < Lindrian> oh right, pseq evaluates the left before returning the right, guaranteed.
16:32 < Lindrian> So the difference between seq and pseq is that pseq guarantees it while seq doesnt?
16:51 < qu1j0t3> well, thread API has proven to be a poor fit for many purposes.
16:53 < zwer_z> > seq (error "one") (error "two")
16:53 < lambdabot> *Exception: one
16:53 < Lindrian> > pseq (error "first") (error "second")
16:53 < lambdabot> Not in scope: ‘pseq’
16:53 < lambdabot> Perhaps you meant ‘seq’ (imported from Prelude)
16:54 < zwer_z> IIRC in ghc seq will always evaluate to error "one", while
haskell (the language) allows either
16:55 < Lindrian> i read seq as "try to evaluate the first argument, but compiler might think otherwise"
16:55 < ski> Lindrian : yes, `pseq a b' guarantees `a' is forced before `b'. `seq a b' doesn't
16:56 < ski> (i think in `seq a b' you're not even guaranteed that `a' is forced before `b' is
returned .. as long as it will happen eventually)
16:56 < zwer> ski I think there's a lack of guarantee only if both a and b are bottom.
16:57 < zwer> > seq (error "foo") 10
16:57 < lambdabot> *Exception: foo
16:57 < zwer> whereas that should always evaluate to bottom
16:58 < benzrf> iirc
16:58 < ski> zwer : consider `seq (seq (error "foo") ()) (error "bar")' -- i think this can legally
raise `error "bar"'
16:58 < benzrf> the haskell spec only says
16:58 < benzrf> seq bottom anything = bottom
16:58 < ski> yes
16:58 < benzrf> seq anything bottom = bottom
16:58 < zwer> ski I think so too. if b is bottom a does not have to be evaluated at all
17:00 < ski> zwer : in this case "`b'" for the inner call is not bottom
17:02 < Lindrian> so seq will try to evaluate to WHNF?
17:02 < Lindrian> pseq guarantees WHNF
17:03 < zwer> ski a is entire inner seq, which may not be evaluated
17:05 < ski> yes
17:05 < ski> (i think i used a different argument, though. i can't recall it atm)
17:06 < ski> Lindrian : both will evaluate to WHNF. `pseq' guarantees sequential *ordering*.
`seq' just guarantees that both will be forced
17:07 < Lindrian> pseq guarantees the first argument is evaluated to WHNF before the second,
while seq doesnt. Ok.
17:07 < ski> `seq' is specified using "denotational semantics", which only talks about the
final value/denotation of an evaluation, not how you can get to it
17:08 < ski> `pseq' would need to be specified using "operational semantics", which talks
in terms of rewriting steps (so there's an inherent ordering that we talk
about here)
17:08 * ski nods to Lindrian
```
================================================
FILE: guide-de.md
================================================
# Die Einführung
Das ist mein empfohlener Weg Haskell zu lernen.
*Beachte: Diese Einführung ist zwar in Deutsch, aber alle Referenzen sind leider noch in Englisch.*
#### Denk an folgendes: *Mach dir nichts draus, wenn du etwas nicht direkt verstehst*. Einfach weiter machen.
## Community
Unser IRC channel auf Freenode ist `#haskell-beginners`.
IRC web client [hier](http://webchat.freenode.net/).
Die Haskell [Mailing Listen](https://wiki.haskell.org/Mailing_lists).
### Community Richtlinien
[Siehe Chris Done's Post über Lehre](http://chrisdone.com/posts/teaching)
Sei freundlich und höflich. Unfreundlichkeit und Unhöflichkeit schreckt Leute ab, sodass sie nicht mehr mitmachen wollen.
Wenn du dir keine Mühe bei deiner Kritik gibst, hilft sie der Person, die sie erhält, auch nicht.
Beschreibe Dinge nicht als "einfach" oder "trivial". Leute, die hart für ihren Fortschritt arbeiten müssen, werden sich schlecht fühlen deswegen.
Langsame Lerner sind meistens die sorgfältigsten, das sollte gewürdigt werden!
Keine geheuchelte Überraschung. Spiele nicht überrascht, wenn jemand sagt, dass er etwas nicht weiß. Du erreichst nur, dass jemand sicht schlecht fühlt und du dich besonders toll.
Kein "also, eigentlich ...". Wenn jemand etwas sagt, das nahezu richtig ist - aber nicht exakt - und du sagst, "also, eigentlich..." und gibst eine kleine Korrektur. Das ist
besonders unnötig, da es keine Nutzen für die eigentlich Konversation hat. Das heißt nicht, dass die Recurse Center nicht an Richtigkeit oder Genauigkeit interessiert ist.
Fast alle "also, eigentlich" sind Selbstdarstellung und keine konstruktiven Verbesserungen.
Kein ständiges Reinreden. Wenn du siehst wie jemand ein Problem durcharbeitet, sollest du nicht immer wieder Vorschläge einwerfen. Lass es ihn herausfinden außer er fragt
nach Hilfe. Unterbrechungen zu vermeiden ist [eine der Gründe für #haskell-beginners](http://chrisdone.com/posts/teaching).
Rassismus, Sexismus, Homophobie, Transphobie und andere Arten von Vorurteilen sind nicht erwünscht und werden nicht toleriert.
---
Richtlinien aus [the Recurse Center manual](https://www.recurse.com/manual). Danke für die Veröffentlichung Recurse Center.
# Was sind Haskell, GHC, und Cabal?
Haskell ist eine Programmiersprache, die in einem Report festgelegt wird, der letzte ist von 2010.
Der Report ist [online](http://www.haskell.org/onlinereport/haskell2010/) verfügbar.
## GHC
[GHC](http://www.haskell.org/ghc/) ist der beliebteste und bekannteste Weg mit Haskell zu arbeiten.
Er beinhaltet einen Compiler, REPL (Interpreter), Paket Management, und ein paar weitere Dinge.
## Cabal
[Cabal](https://www.haskell.org/cabal/download.html) ist für Projekt Management und
Abhängigkeitsauflösung zuständig. Hiermit installierst du Projekte, normalerweise in ihre
eigene Sandbox.
Cabal ist äquivalent zu Rubys Bundler, Pythons pip, Nodes NPM, Maven, etc. GHC
kümmert sich selber um die Paketierung, Cabal wählt die zu installierende Version aus.
# Installation
## Ubuntu
[Dieses PPA](http://launchpad.net/~hvr/+archive/ghc) ist ausgezeichnet und ich benutze
es auf allen meine Linux Entwicklungs- und Buildmaschinen.
Genauer:
```bash
$ sudo apt-get update
$ sudo apt-get install python-software-properties # v12.04 and below
$ sudo apt-get install software-properties-common # v12.10 and above
$ sudo add-apt-repository -y ppa:hvr/ghc
$ sudo apt-get update
$ sudo apt-get install cabal-install-1.20 ghc-7.8.3 happy-1.19.4 alex-3.1.3
```
Dann füge das folgende zu deinem `$PATH` (bash\_profile, zshrc, bashrc, etc) hinzu:
```
~/.cabal/bin:/opt/cabal/1.20/bin:/opt/ghc/7.8.3/bin:/opt/happy/1.19.4/bin:/opt/alex/3.1.3/bin
```
*Optional:* Du kannst auch `.cabal-sandbox/bin` zu deinem PATH hinzufügen. Code, der gerade
entwickelt wird, ist dann verfügbar über die Kommandozeile. Das funktioniert aber nur,
wenn das aktuelle Verzeichnis eine Cabal Sandbox ist.
## Debian
### Ubuntu PPA nutzen
Wenn du nicht stable benutzt, kannst du dieselben Schritte wie unter Ubuntu ausführen, aber du musst
ein weiteres Kommando ausführen. Direkt nachdem
`sudo add-apt-repository -y ppa:hvr/ghc` ausgeführt wurde, starte:
```bash
$ sudo sed -i s/jessie/trusty/g /etc/apt/sources.list.d/hvr-ghc-jessie.list
```
Für alle anderen Debian Versionen, ersetze einfach alle Vorkommen von `jessie` mit dem entsprechenden
Versionsnamen im Kommando oben.
Wenn, warum auch immer, die Datei `/etc/apt/sources.list.d/hvr-ghc-jessie.list` nicht existiert,
dann sollte `/etc/apt/sources.list` eine Liste, wie die folgende beinhalten:
deb http://ppa.launchpad.net/hvr/ghc/ubuntu jessie main
Ersetze `jessie` durch `trusty` in dieser Zeile.
### Manuell Kompilieren
Du kannst
[dieser](http://www.davesquared.net/2014/05/platformless-haskell.html) Anleitung folgen
(geschrieben für Mac OS X):
Anmerkungen:
- Setze deinen Präfix entsprechend, wenn du GHC konfiguierst
- Anstatt die `cabal-install` Binary zu laden, lade die Quellen und führe das Skript
`bootstrap.sh` aus.
## Fedora 21
Um Haskell 7.8.4 aus dem unoffiziellen Repo (Fedora 22+ wird es in den offiziellen beinhalten)
zu installieren:
```bash
$ sudo yum-config-manager --add-repo \
> https://copr.fedoraproject.org/coprs/petersen/ghc-7.8.4/repo/fedora-21/petersen-ghc-7.8.4-fedora-21.repo
$ sudo yum install ghc cabal-install
```
Wie in auf der Seite
[petersen/ghc-7.8.4 copr](https://copr.fedoraproject.org/coprs/petersen/ghc-7.8.4/)
beschrieben kann dieser ghc nicht parallel zu Fedora/EPEL ghc installiert werden.
## Arch Linux
Um Haskell aus den offiziellen Repos unter Arch Linux zu installieren, mache folgendes:
```bash
$ sudo pacman -S cabal-install ghc happy alex haskell-haddock-library
```
## Gentoo
Unter Gentoo kannst du verschiedene Komponenten der Haskell Platform
via Portage installieren. Wenn du `ACCEPT_KEYWORDS=arch` nutzt (anstatt
`ACCEPT_KEYWORDS=~arch`), installiert Portage die uralt Versionen der verschiedenen
Haskell Teile. Daher füge, wenn du, und *nur* wenn du `ACCEPT_KEYWORDS=arch` nutzt, das
Folgende in `/etc/portage/package.accept_keywords` ein.
dev-haskell/cabal-install ~arch
dev-lang/ghc ~arch
Wenn das getan ist:
```bash
$ emerge -jav dev-lang/ghc dev-haskell/cabal-install
```
Gentoo hat eine "stabile" (lies: alte) Version von `cabal-install` im Portage
tree, daher wirst du `cabal-install` nutzen wollen um eine neuere version zu installieren.
Beachte, dass backslashes Absicht sind.
```bash
$ \cabal update # The backslashes
$ \cabal install cabal-install # are intentional
```
Du hast cabal jetzt global mit Portage und lokal in deinem Home Verzeichnis mit
`cabal-install` installiert. Der nächste Schritt ist sicherzustellen, dass, wenn du
`cabal` im Terminal ausführst, die aktuelle Version genommen wird.
Dafür kannst du folgende Zeilen zur Konfiguration deiner Shell hinzufügen:
```bash
PATH=$PATH:$HOME/.cabal/bin
alias cabal="$HOME/.cabal/bin/cabal"
```
Wenn du nicht weißt, was für eine Shell du nutzt, ist es mit hoher Wahrscheinlichkeit die Bash.
Wenn du die Bash nutzt, musst du die Datei `~/.bashrc` editieren. Wenn du die Z-shell nutzt, ist
die Datei `~/.zshrc`. Du kannst folgendes Kommando ausführen, um herauszufinden, was für eine Shell
du benutzt:
```bash
echo $SHELL | xargs basename
```
Ich nutze zsh, daher ist die Ausgabe `zsh`, wenn ich es ausführe.
Wenn du all das getan hast, brauchst du die weiteren Tools`alex` und
`happy`.
```bash
$ cabal install alex happy
```
Glückwunsch! Du hast jetzt eine funktionierende Haskell installation!
## Mac OS X
### 10.9
Installiere die [GHC for Mac OS X](http://ghcformacosx.github.io/) App, welche
GHC und Cabal beinhaltet. Sie liefert Anweisungen, wie du GHC und Cabal zu deinem
path hinzufügen kansnt, nachdem du die `.app` irgendwo ableget hast.
### 10.6-10.8
Installiere die Binary Distribution, wie unten beschrieben, mit [diesem tarball](https://www.haskell.org/platform/download/2014.2.0.0/ghc-7.8.3-x86_64-apple-darwin-r3.tar.bz2).
## Windows
- Der [minimale ghc Installer für Windows](http://neilmitchell.blogspot.com/2014/12/beta-testing-windows-minimal-ghc.html)
ist in der Lage `network` und andere zu installieren. Technisch gesehen befindet er sich in der Beta, sollte aber für die Zwecke eines jeden der diese Anleitung ließt funktionieren.
Vergesse nicht den Installer als Administrator auszuführen, da er in deinen Programmen installieren will.
## Andere Linux Nutzer
Lade die aktuellen Binary Distributions für cabal und ghc:
- [GHC](http://www.haskell.org/ghc/).
- [Cabal](https://www.haskell.org/cabal/download.html).
#### Detailierte Installationsanleitung für Mac OS X
Du musst das nicht machen, wenn du die .app nutzt, aber wenn das für dich nicht funktioniert, versuche
[das](http://www.davesquared.net/2014/05/platformless-haskell.html) mit der Binary Distribution.
# Grundlegende Kurse
## Yorgey's cis1940 Kurs
> *Den solltest du zuerst machen*, das ist eine erstklassige Einführung
> in Haskell, die ich sehr empfehle
Verfügbar [online](https://www.seas.upenn.edu/~cis1940/spring13/lectures.html).
[Brent Yorgey](https://byorgey.wordpress.com)s Kurs ist der beste, den ich bisher gefunden habe.
Dieser Kurs ist wertvoll, da du nicht nur Grundlegendes über Haskell lernst, sondern auch lernst
Parser Combinators zu verstehen.
Der einzige Fall, in dem du nicht mit cis1940 anfangen solltest, ist, wenn du kein oder ein unerfahrener
Programmierer bist. Wenn das der Fall ist, starte mit
[Thompsons Buch](https://www.haskellcraft.com/craft3e/Home.html) und gehe über zu
cis1940.
---
## FP Kurs
> Das ist der Kurs, den ich nach Yorgeys cis1940 Kurs empfehle zu machen
Verfügbar [hier](https://github.com/bitemyapp/fp-course) auf github
Das wird dein Verständnis verbessern und dir Erfahrung mit der Implementierung der
Abstraktionen geben, die in cis1940 eingeführt wurden, das ist die Praxis, die *ausschlaggebend* ist, um
mit der üblichen Nutzung von Functor/Applicative/Monad/etc. in Haskell vertraut zu werden.
Erst cis1940 und dann den FP Kurs zu machen, ist die wesentliche Empfehlung meiner Anleitung
und ist der Weg, wie ich anderen Leuten Haskell beibringe.
---
## Deutsche Ressourcen
*Anmerkung: Dieser Abschnitt wurde bei der Übersetzung eingefügt, um hilfreiche deutsche Inhalte zu verlinken*
* [funktionale-programmierung.de](http://funktionale-programmierung.de/tags-archive.html#Haskell) ist ein Blog über Funktionale Programmierung
im Allgemeinen, welcher auch Posts über Haskell beinhaltet.
* [Skript](http://verify.rwth-aachen.de/fp14/FP14.pdf) der Vorlesung Funktionale Programmierung an der RWTH Aachen. Beinhaltet eine kurze Einführung
in Haskell, sowie Kapitel über den Lambda Kalkül und Typüberprüfung und -inferenz.
---
## Zusätzliche Kurse cs240h
> Stellt weiteres Material für fortgeschrittene Themen bereit
Verfügbar [online](http://www.scs.stanford.edu/14sp-cs240h/).
Das ist [Bryan O'Sullivan](https://github.com/bos)s online Version des Kurses, den er
in Stanford unterrichtet. Wenn du nicht weißt, wer er ist, guck dir der Hälfte der Libraries
an, die jede Haskell Anwendung am Ende braucht und sein Name wird dabei sein.
Wenn du bereits den Yorgey Kurs gemacht hast, sind die Module über
phantom types, information flow control, language extensions, concurrency,
pipes, und lenses von besonderer Bedeutung.
---
## Referenz Material für die drei Kurse
[Learn You a Haskell for Great Good (LYAH)](http://learnyouahaskell.com) und
[Real World Haskell](http://book.realworldhaskell.org) (Danke bos!) sind
online verfügbar.
I empfehle RWH als Referenz (dickes Buch). Die Kapitel über Parsen und Monaden
sind sehr gut, um ein Verständnis dafür zu kriegen, wofür Monaden nützlich sind. Andere Leute sagen,
dass sie es oft verlinkt haben. Vermutlich eine gute Nachbereitung für die praktischen Teile
nachdem du die essentiellen Sachen in Haskell verstanden hast?
### Was macht dieser `<-` / `do` / list comprehension syntaktische Zucker?
Exzellenter [Artikel](http://www.haskellforall.com/2014/10/how-to-desugar-haskell-code.html).
### Um Listen und Fold zu verstehen
- [Explain List Folds to Yourself](http://vimeo.com/64673035)
### Um ein paar wesentliche Typ Klassen zu lernen
Nützlich um `Functor`, `Applicative`, `Monad`, `Monoid` und andere
Typ Klassen im Allgemeinen zu verstehen aber auch etwas Hask-bezogene Kategorien Theorie:
- Die [Typeclassopedia](http://www.haskell.org/haskellwiki/Typeclassopedia)
### Die grundlegenden Haskell Fehler Meldungen verstehen
- [Understanding basic error messages](http://ics.p.lodz.pl/~stolarek/_media/pl:research:stolarek_understanding_basic_haskell_error_messages.pdf)
---
# Laziness, strictness, guarded recursion
- Marlows [Buch](http://chimera.labs.oreilly.com/books/1230000000929/ch02.html)
über Parallelisierung und Nebenläufigkeit hat eine der besten Einführungen über
laziness und normal form, die ich finden konnte. Nutze anderes Material, wenn es nicht direkt
verständlich ist.
- [More points for lazy evaluation](http://augustss.blogspot.hu/2011/05/more-points-for-lazy-evaluation-in.html)
- [Oh my laziness!](http://alpmestan.com/posts/2013-10-02-oh-my-laziness.html)
- SO Frage '[Does haskell have laziness?](https://stackoverflow.com/questions/13042353/does-haskell-have-tail-recursive-optimization)'
- [Johan Tibell](https://github.com/tibbe)s Folien von seinem Vortrag
[reasoning about laziness](http://www.slideshare.net/tibbe/reasoning-about-laziness).
## Kurze Demonstration
```haskell
let a = 1 : a -- guarded recursion, (:) is lazy and can be pattern matched.
let (v : _) = a
> v
1
> head a -- head a == v
1
let a = 1 * a -- not guarded, (*) is strict
> a
*** Exception: <<loop>>
```
# IO
- [Evaluation order and State tokens](https://www.fpcomplete.com/user/snoyberg/general-haskell/advanced/evaluation-order-and-state-tokens)
- [Unraveling the mystery of the IO monad](http://blog.ezyang.com/2011/05/unraveling-the-mystery-of-the-io-monad/).
- [First class "statements"](http://blog.jle.im/entry/first-class-statements).
- [Haddocks for System.IO.Unsafe.unsafePerformIO](http://hackage.haskell.org/package/base-4.7.0.1/docs/System-IO-Unsafe.html#v:unsafePerformIO)
Lies die Dokumentation und Implementierung von unsafeDupablePerformIO
Kommentar auf Reddit von `glaebhoerl`
Übersetzt:
> Interessante Randbemerkung: GHC muss die state token Darstellung hinter
> einem abstrakten IO Typ verstecken, weil der state token immer linear benutzt werden muss (nicht
> dupliziert oder dropped(??)), aber das Typsystem kann das nicht erzwingen. Clean, ein andere
> lazy Haskell-ähnliche Sprache, hat eindeutige Typen (die ähnliche zu Linearen Typen sind
> und vermutlich anders in vielen Aspekten, die mir nicht bekannt sind), und sie stellen
> World-passing(??) direkt und eine (nicht abstrakte) IO Monade nur der Einfachheit halber
> bereit.
Original:
> Interesting side note: GHC needs to hide the state token representation behind
> an abstract IO type because the state token must always be used linearly (not
> duplicated or dropped), but the type system can't enforce this. Clean, another
> lazy Haskell-like language, has uniqueness types (which are like linear types
> and possibly different in ways I'm not aware of), and they expose the
> World-passing directly and provide a (non-abstract) IO monad only for
> convenience.
# Monaden und Monaden Transformer (monad transformers)
> Versuche nicht diese zu lernen bis du nicht Typ Klassen, Monoide, Funktoren
> und Applikativen verstanden hast
Implementiere die Monaden aus der Standard Bibliothek ( List, Maybe, Cont, Error, Reader,
Writer, State ) für dich selbst, um sie besser zu verstehen. Dann schreibe vielleicht einen
monadischen Interpreter für eine kleine Expression Sprache mit dem
[Monad Transformers Step by Step](http://catamorph.de/documents/Transformers.pdf)
Paper (erwähnt in 'monad transformers' im folgenden).
Mehrere Interpreter zu schreiben, indem man einfach nur die Monade ändert um die Semantik zu verändern
kann helfen, zu verstehen was passiert.
Zusätzlich, implementiere `Control.Monad` selbst. Funktionen wie `mapM` oder `sequence` sind gute
Möglichkeiten, um zu üben, generischen monadischen Code zu schreiben.
Der FP Kurs kann als Anleitung für diese Prozess genutzt werden, was auch beinhaltet
eine eigene Applicative zu schreiben.
Credits:
- Reddit Kommentar von htmltyp und Crandom [hier](https://www.reddit.com/r/haskell/comments/29eke6/basic_program_ideas_for_learning_about_monads/cik5aj6).
- Reddit Kommentar von jozefg [hier](https://www.reddit.com/r/haskell/comments/29eke6/basic_program_ideas_for_learning_about_monads/cik5trg).
## Monad transformers
- [A gentle introduction to Monad Transformers](https://github.com/kqr/gists/blob/master/articles/gentle-introduction-monad-transformers.md).
- [Monad transformers step-by-step](http://catamorph.de/documents/Transformers.pdf).
# Testen, Tests, Specs, generative/property testing
- Dieses [Tutorial](https://github.com/kazu-yamamoto/unit-test-example/blob/master/markdown/en/tutorial.md) von Kazu Yamamoto ist fantastisch.
- [Simple-Conduit](https://github.com/jwiegley/simple-conduit): Gute, einfache
Bibliothek um zu lernen, wie streaming IO funktioniert im Allgemeinen, die Konzepte
sind transferierbar auf Bibliotheken wie Pipes und Conduit
# Parsen in Haskell
- Parser combinator [tutorial](https://github.com/JakeWheat/intro_to_parsing)
für Haskell mit Parsec
- [Writing your own micro-Parsec](http://olenhad.me/articles/monadic-parsers/)
## Parsen und generieren von JSON
Aeson ist die standard Lösung für parsen von [JSON](https://json.org) in
Haskell. Verfübar über [hackage](https://hackage.haskell.org/package/aeson) und
[github](https://github.com/bos/aeson).
- [Parsing JSON using Aeson](http://blog.raynes.me/blog/2012/11/27/easy-json-parsing-in-haskell-with-aeson/)
- [Aeson and user created types](http://bitemyapp.com/posts/2014-04-11-aeson-and-user-created-types.html)
- [Parsing non-deterministic data with aeson and sum types](http://bitemyapp.com/posts/2014-04-17-parsing-nondeterministic-data-with-aeson-and-sum-types.html)
- [Aeson tutorial](https://www.fpcomplete.com/school/starting-with-haskell/libraries-and-frameworks/text-manipulation/json)
# Graph Algorithmen und Datenstrukturen
- Das [fgl Paket](https://hackage.haskell.org/package/fgl) im Besonderen die
puren, funktionalen kürzester Pfad [Algorithmen](http://hackage.haskell.org/package/fgl-5.4.2.2/docs/Data-Graph-Inductive-Query-SP.html).
- [Inductive graphs and Functional Graph Algorithms](http://web.engr.oregonstate.edu/~erwig/papers/abstracts.html#JFP01).
- [FGL/Haskell - A Functional Graph Library](http://web.engr.oregonstate.edu/~erwig/fgl/haskell/old/fgl0103.pdf).
- [Data.Graph Quellcode vom Containers Paket](http://hackage.haskell.org/package/containers-0.5.5.1/docs/Data-Graph.html).
- Das [graphs Paket](https://hackage.haskell.org/package/graphs).
- [SO Frage zu PHOAS](https://stackoverflow.com/questions/24369954/separate-positive-and-negative-occurrences-of-phoas-variables-in-presence-of-rec)
- [PHOAS for free](https://www.fpcomplete.com/user/edwardk/phoas).
- [Tying the Knot](http://www.haskell.org/haskellwiki/Tying_the_Knot).
- [Hackage: dag](https://hackage.haskell.org/package/dag).
# Entwicklungsumgebung
## Emacs
- [Alejandro Serrass Tutorial](https://github.com/serras/emacs-haskell-tutorial/blob/master/tutorial.md)
- [Meine dotfiles](https://github.com/bitemyapp/dotfiles/)
*Anmerkung: Dotfiles sind die Konfigurationsdateien für Shell und Editor, wie z.b. `.vimrc`*
- [Chris Done's emacs Konfiuration](https://github.com/chrisdone/chrisdone-emacs)
## Vim
- [Vim Seite im Haskell Wiki](http://www.haskell.org/haskellwiki/Vim)
- [Haskell-vim-now](https://github.com/begriffs/haskell-vim-now)
- [GHC-Mod](https://github.com/kazu-yamamoto/ghc-mod)
- [GHC-Mod vim plugin](https://github.com/eagletmt/ghcmod-vim)
- [Hindent](https://github.com/chrisdone/hindent)
## Sublime Text
- [SublimeHaskell](https://github.com/SublimeHaskell/SublimeHaskell)
# Arbeiten mit Cabal
## Cabal Leitfaden
Cabal Hell war ein Problem für Haskell Nutzer vor der Einführung von
Sandboxes. Eine Installation außerhalb einer sandbox wird in die user
package-db installieren. Das ist *keine* gute Idee außer für grundlegende Pakete wie
Cabal, alex, und happy. Nichts anderes sollte in den user oder der globalen
package-db installiert sein, außer du weißt was du tust
[Hier](http://softwaresimply.blogspot.com/2014/07/haskell-best-practices-for-avoiding.html) gibt es ein
paar gute Praktiken um Cabal hell zu verhindern.
Um mit einem Paket zu experimentieren oder ein Projekt zu starten, beginne mit
`cabal sandbox init` in einem neuen Verzeichnis.
Kurz gesagt:
- Nutze immer Sandboxes, um neue Pakete zu installieren, neue oder existierende Projekte zu bauen oder
Experimente zu starten
- Nutze `cabal repl` um eine Projekt bezogene ghci Instanz zu starten
Die vorgeschlagene, sandbox-basierte Methode sollte Paket Abhängigkeits Probleme vermeiden
aber sie ist inkompatibel zu der Art wie die Haskell Plattform fertig gebaute Pakete bereitstellt.
Wenn du momentan noch Haskell lernst und nicht verstehst wie ghc-pkg und Cabal funktionieren,
*nutze nicht die Plattform* und stattdessen die Instruktionen, die zu Beginn erklärt wurden.
## Stackage
Für alle Nutzer (normalerweise Yesod Nutzer), die Build Probleme haben, zieht Stackage in Erwägung:
- Eine gute Zusammenfassung ist
[hier](https://www.fpcomplete.com/blog/2014/05/stackage-server).
Der Meinung des Authors nach, ist Stackage normalerweise nützlicher als ein `cabal freeze`.
# Hoogle und Haddock
## Suche Code nach der Typ Signatur
Die [Hoogle Suchmaschine](http://www.haskell.org/hoogle/) kann nach Typen suchen.
Zum Beispiel, guck dir die such Resultate für `(a -> b) -> [a] -> [b]`
[an](http://www.haskell.org/hoogle/?hoogle=%28a+-%3E+b%29+-%3E+%5ba%5d+-%3E+%5bb%5d).
Auch verfügbar über FPComplete [hier](https://www.fpcomplete.com/hoogle).
Außerdem gibt es [Hayoo](http://holumbus.fh-wedel.de/hayoo/hayoo.html) (welches standardmäßig ganz
hackage durchsucht).
## Eine eigene lokale Instanz von Hoogle aufsetzen
Siehe [hier](https://gist.github.com/bitemyapp/3e6a015760775e0679bf).
## Haddock
1. [Fix your hackage documentation](http://fuuzetsu.co.uk/blog/posts/2014-01-06-Fix-your-Hackage-documentation.html)
2. [Hackage Dokumentation v2](http://fuuzetsu.co.uk/blog/posts/2014-01-06-Hackage-documentation-v2.html)
Beachte, dass diese Artikel *etwas veraltet* sind: Zum Beispiel hat Hackage jetzt eine neue
Info mit Dokumentations- und Build-Status.
## Was du wirklich wissen solltest
Damit Haddock Dokumentation für verwandte Pakete inkludiert, musst du `documentation: True`
in deiner `~/.cabal/config` setzen. Wenn es auf Standard Wert (`False`) gelassen wurde,
musst du alle Pakete löschen und neu installieren bevor die Haddocks generiert werden.
Die andere Sache, an die man denken sollte, ist, dass aufgrund der Art wie `$pkg` interpoliert
wird *von* cabal, nicht von dir, die `html-location` und `content-location` Parameter
*in Apostrophen* stehen *müssen* und in die Shell eingegeben werden oder in einem Shell Skript stehen.
Sie werden nicht in einer Makefile funktionieren, da Make denken wird es seien Make Variablen.
```bash
#! /usr/bin/env sh
# You can write it one one line by skipping the backslashes
cabal haddock --hoogle --hyperlink-source \
--html-location='http://hackage.haskell.org/package/$pkg/docs' \
--contents-location='http://hackage.haskell.org/package/$pkg'
```
# TravisCI
Wenn du, wie ich, ein großer Fan von [TravisCI](https://travis-ci.org) bist, dann empfehle
ich *sehr* [multi-ghc-travis](https://github.com/hvr/multi-ghc-travis) anzugucken für die Basis
der `travis.yml` für deine Haskell Projekte.
# Frontend/JavaScript
Wir haben eine große Auswahl! Im Grunde gibt es drei Möglichkeiten,
die ich empfehlen würde:
* [Haste](http://haste-lang.org/) ein Haskell zu JavaScript Compiler
- Der [Compiler](https://github.com/valderman/haste-compiler) auf github.
- Eine tolle
[Demo](http://www.airpair.com/haskell/posts/haskell-tutorial-introduction-to-web-apps)
von Haste mit einem Beispiel Projekt.
* [GHCJS](https://github.com/ghcjs/ghcjs)
- [GHCJS Einführung](http://weblog.luite.com/wordpress/?p=14)
- [Functional Reactive Web Interfaces with GHCJS and Sodium](http://weblog.luite.com/wordpress/?p=127)
- [Writing Atom plugins in Haskell using ghcjs ](http://edsko.net/2015/02/14/atom-haskell/)
* [PureScript](http://www.purescript.org/)
- Nicht direkt Haskell, wie Haste und GHCJS, aber eine beliebte Wahl unter Haskellern
- Geschrieben in und inspiriert durch Haskell
- Teste Purescript in deinem Browser [hier](http://try.purescript.org/)
- Gute Anleitung für [die ersten Schritte](http://www.christopherbiscardi.com/2014/06/22/getting-started-with-purescript/)
## Welche Frontend Sprache nutze ich?
GHCJS und Haste sind beide komplett Haskell. GHCJS wird mit mehr Haskell
Paketen funktionieren als Haste, aber ist egal für viele Frontend Projekte.
Purescript ist kein Haskell, daher ist es nicht möglich Code direkt
mit dem Backend zu teilen.
GHCJS hat den größten Laufzeit Overhead mit über 100kb (luite arbeitet daran).
Haste und Purescript sind vergleichbar.
PureScript hat die beste JS Tooling Integration (nutzt gulp/grunt/bower), GHCJS
und Haste integrieren besser mit Haskells Tooling (Cabal).
Alle drei sind eine gute Wahl und werden für die meisten Frontend Projekte genügen.
# Für ein tiefergehendes Verständnis für Laziness, NF, WHNF
- [Notes on lambda calculus](https://vec.io/posts/notes-on-lambda-calculus).
## Forschungs Paper über Lazy Lambda Calculi
- [A call by need lambda calculus](http://homepages.inf.ed.ac.uk/wadler/topics/call-by-need.html#need-journal).
- [Demonstrating Lambda Calculus Reduction](http://www.itu.dk/~sestoft/papers/sestoft-lamreduce.pdf)
- [The lazy lambda calculus](http://www.cs.ox.ac.uk/files/293/lazy.pdf).
- [Lazy evaluation of Haskell](http://www.vex.net/~trebla/haskell/lazy.xhtml)
# Parallelisierung/Nebenläufigkeit
- [Parallel and Concurrent Programming in Haskell](http://chimera.labs.oreilly.com/books/1230000000929). Dieses
Buch von Simon Marlow ist vermutlich das beste, was ich je gelesen habe über
Parallelisierung und Nebenläufigkeit.
- Ein ausführliches [Tutorial](http://kukuruku.co/hub/haskell/haskell-testing-a-multithread-application)
über Testen & schrittweise Entwicklung einer Multi-thread Anwendung in
Haskell.
- [Functional Reactive Programming](http://www.haskell.org/haskellwiki/Functional_Reactive_Programming)
# Lenses und Prisms
Nachdem du vertraut bist mit Haskell, solltest du unbedingt in Betracht ziehen
Lenses und Prims zu lernen, auch wenn du nur ein "Nutzer" bist. Du brauchst nicht
du zu grunde liegende Kategorie zu verstehen damit es nützlich ist.
Die Schwierigkeit Lens zu nutzen wird oft stark überschätzt. Jeder der vertraut ist
mit Functor/Foldable/Traversable (oder nur dem ersten der drei) kann Lenses und
Prisms bereits nutzen, um sein Leben leichter zu machen.
Wenn du jemals etwas wie `(fmap . fmap)` gemacht hast, hast du bereits in deinem
Kopf "lensing" gemacht.
Ich empfehle zwei dieser Tutorials/Einführungen:
- [A little lens starter tutorial](https://www.fpcomplete.com/school/to-infinity-and-beyond/pick-of-the-week/a-little-lens-starter-tutorial)
- [Lens: Lenses, Folds and Traversals](https://github.com/ekmett/lens#lens-lenses-folds-and-traversals)
Siehe hier für weitere Informationen: [Lens Paket auf Hackage](http://hackage.haskell.org/package/lens).
# Recursion Schemes
Einige der verrückten \*-morphismus wörter, die du gehört hast, sind eigentlich
über Rekursion. Beachte - Bevor du diese Material betrachtest, solltest du wissen,
wie man foldr für Listen implementiert und mindestens eine andere Datenstruktur,
wie z.B. einen Baum (folds sind Catamorphismen). Wenn du auch noch weißt, wie man
ein unfold (Anamorphismus) implementiert, ist das hilfreich.
Diese Material passt gut mit Traversable und Foldable zusammen.
- [An introduction to recursion schemes](http://patrickthomson.ghost.io/an-introduction-to-recursion-schemes/)
- [Don't fear the cat](http://fho.f12n.de/posts/2014-05-07-dont-fear-the-cat.html) -
Gute Demonstration, warum Hylomorphismus die Komposition von cata und ana ist
- [Recursion Schemes](http://comonad.com/reader/2009/recursion-schemes/) - Diese
Einführung ist echt gut.
- [Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire](http://eprints.eemcs.utwente.nl/7281/01/db-utwente-40501F46.pdf)
- [Catamorphisms](https://www.fpcomplete.com/user/edwardk/recursion-schemes/catamorphisms)
# GHC Core und Performance Verbesserungen
- [Write Haskell as Fast as C](write_haskell_as_fast_as_c.md)
- [GHC Wiki: CoreSyn Type](https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/CoreSynType).
- [Hackage: GHC Core](https://hackage.haskell.org/package/ghc-core).
- [Stackoverflow Frage: Reading GHC Core](https://stackoverflow.com/questions/6121146/reading-ghc-core).
- [Haskell as fast as C](http://donsbot.wordpress.com/2008/06/04/haskell-as-fast-as-c-working-at-a-high-altitude-for-low-level-performance/).
- [Real World Haskell, Kapitel 25: Profiling and Optimizations](http://book.realworldhaskell.org/read/profiling-and-optimization.html).
# Typ und Kategorien Theorie
> *Nicht* notwending um in Haskell zu entwickeln, nur für Interessierte!
Wenn du dich mit Typ- oder Kategorien Theorie beschäftigen willst:
- [Catster's Guide](http://byorgey.wordpress.com/2014/01/14/catsters-guide/) und
[Catster's Guide 2](http://byorgey.wordpress.com/catsters-guide-2/)
- Das [Haskell Wikibuch](http://en.wikibooks.org/wiki/Haskell/Category_theory)
hat anschauliche Abbildungen
- [Category Theory](http://www.haskell.org/haskellwiki/Category_theory) im
Haskell Wiki hat auch gute Links zu anderen Ressourcen
- [Categories from scratch](http://science.raphael.poss.name/categories-from-scratch.html), beinhaltet ein paar praktische Beispiele
- Pierces [Great Works in PL](http://www.cis.upenn.edu/~bcpierce/courses/670Fall04/GreatWorksInPL.shtml) Liste.
## Bücher
- [Quora Frage: What is the best textbook for category theory?](http://www.quora.com/Category-Theory/What-is-the-best-textbook-for-Category-theory?share=1) Kmett's recommendations
- [Awodey](http://ukcatalogue.oup.com/product/9780199237180.do) und
[MacLane](http://www.amazon.com/Categories-Working-Mathematician-Graduate-Mathematics/dp/0387984038).
Die Standard Bücher über Kategorien Theorie.
- [Harper's Practical Foundations for Programming Languages](http://www.cs.cmu.edu/~rwh/plbook/book.pdf)
ist die beste auf Programmiersprachen fokussierte Einführung in Typentheorie,
die ich gelesen habe.
- [Type theory and Functional Programming](http://www.cs.kent.ac.uk/people/staff/sjt/TTFP/).
# Andere interessante Themen
## Parametricity, ad-hoc vs. parametric polymorphism, free theorems
- [Parametricity](tony_parametricity.pdf).
- [TeX Quellen](https://github.com/tonymorris/parametricity/) für den Vortrag
von oben.
- [Making ad-hoc polymorphism less ad-hoc](http://swizec.com/blog/week-20-making-ad-hoc-polymorphism-less-ad-hoc/swizec/6564).
- [Theorems for Free!](http://ttic.uchicago.edu/~dreyer/course/papers/wadler.pdf).
## Initial und Final, DSLs, Finally Tagless
- [Final Encodings, Part 1: A Quick Demonstration](http://creativelad.wordpress.com/2013/11/28/final-encodings-part-1-a-quick-demonstration/).
- [Transforming Polymorphic Values](http://martijn.van.steenbergen.nl/journal/2009/10/18/transforming-polymorphic-values/).
- [GADTs in Haskell 98](http://martijn.van.steenbergen.nl/journal/2009/11/12/gadts-in-haskell-98/).
- [Typed Tagless-Final Linear Lambda Calculus](https://www.fpcomplete.com/user/mutjida/typed-tagless-final-linear-lambda-calculus).
- [Typed tagless-final interpretations: Lecture notes](http://okmij.org/ftp/tagless-final/course/course.html).
- [Typed Tagless Final Interpreters](http://okmij.org/ftp/tagless-final/course/lecture.pdf).
- [The dog that didn't bark](http://existentialtype.wordpress.com/2011/03/21/the-dog-that-didnt-bark/) nicht unbedingt relevant aber interessant.
## Comonads
- [Comonads in Haskell](https://speakerdeck.com/dmoverton/comonads-in-haskell).
- [Stackoverflow Frage: Can a Monad be a Comonad](https://stackoverflow.com/questions/16551734/can-a-monad-be-a-comonad).
## Yoneda / CoYoneda
- [Stackoverflow Frage: Step-by-step explanation of coyoneda](https://stackoverflow.com/questions/24000465/step-by-step-deep-explain-the-power-of-coyoneda-preferably-in-scala-throu).
- Free monads for Less, eine Reihe von drei Artikeln von Edward Kmett
* [Part 1: Codensity](http://comonad.com/reader/2011/free-monads-for-less/).
* [Part 2: Yoneda](http://comonad.com/reader/2011/free-monads-for-less-2/).
* [Part 3: Yielding IO](http://comonad.com/reader/2011/free-monads-for-less-3/).
## Propositions vs. Judgments (computation)
- [StackExchange Frage: What is the difference between propositions and judgements](http://cstheory.stackexchange.com/questions/9826/what-is-the-difference-between-propositions-and-judgments).
- [Vorlesungs Notizen eines kurzen, dreiteiligen Kurses](http://www.ae-info.org/attach/User/Martin-L%C3%B6f_Per/OtherInformation/article.pdf)
# Dependent typing
- [Grokking sum types, value constructors, and type constructors](http://bitemyapp.com/posts/2014-04-05-grokking-sums-and-constructors.html) squint hard.
- [Lightweight Dependent-type Programming](http://okmij.org/ftp/Computation/lightweight-dependent-typing.html).
- [Idris programming language](http://www.idris-lang.org/).
# Statisch gelinkte Binaries
- [Static linking](https://wiki.haskell.org/Web/Literature/Static_linking)
- [Static linking with GHC on Arch Linux](http://www.edofic.com/posts/2014-05-03-ghc-arch-static.html)
- [Statically linking Linux binaries for ARM & MIPS](https://stackoverflow.com/questions/14270177/ghc-statically-linking-linux-binaries-for-arm-mips-processors)
- [Statically link GMP using GHC and LLVM](https://stackoverflow.com/questions/10539857/statically-link-gmp-to-an-haskell-application-using-ghc-llvm)
## Dialog
> In diesem Repository zu finden, siehe [hier](dialogues.md).
Die sind eigentlich sehr wichtig und hilfreich. Schaue hier für tiefere Einblicke
in eine Vielzahl von Themen.
================================================
FILE: guide-el.md
================================================
================================================
FILE: guide-es.md
================================================
# La Guía
Este es el sendero que recomiendo para aprender Haskell.
#### Para tener en consideración: *no te preocupes por las cosas que no entiendes de inmediato*. Continúa a pesar de ello.
## Comunidad
Nuestro canal en IRC es `#haskell-beginners` en Freenode.
Cliente web IRC [aquí](http://webchat.freenode.net/).
La [lista de correo](https://wiki.haskell.org/Mailing_lists) de Haskell.
### Directrices de la Comunidad
[Ver el post de Chris Done sobre enseñanza](http://chrisdone.com/posts/teaching)
Se amable y cortés. Ser odioso y rudo ahuyenta a la gente y les desmotiva a participar.
Criticar por el placer de criticar es solo benéfico para las personas que lo practican, no para los que reciben la crítica.
No describas las cosas como "sencillas" o "simples". Vas a hacer sentir a las personas mal por tener que trabajar tan duro por su progreso. Los que aprenden mas lento son generalmente los mas meticulosos aprendices, ¡lo cual merece aprobación!
No simules sorpresa. No actúes sorprendido cuando alguien reconoce no saber algo, eso hará sentir terrible a la persona y no obtendrás nada excepto hacerte ver sarcástico.
"Mmm...no, de hecho..." Cuando alguien dice algo que es casi pero no completamente correcto y dices, "bueno...no, de hecho..." y luego das una mínima corrección, es especialmente molesto si la corrección que realizas no es lo suficientemente relevante. Esto no significa que al no hacerlo tratamos de ignorar la verdad o que no nos importa ser precisos. El punto es que casi todos los "Mmm... no, de hecho..." son fanfarronerías, no procuradores de la verdad.
No seas el copiloto pesado que siempre esta dando instrucciones al conductor del vehículo.Si ves a alguien trabajando en un problema, no deberías interrumpir intermitentemente para dar consejo. Déjales trabajar hasta que pidan ayuda. Evitar interrupciones es [uno de los principios fundamentales de #haskell-beginners](http://chrisdone.com/posts/teaching).
Ningún sutil -ismo. Racismo, sexismo, homofobia, transfobia u otro tipo de prejuicios no son bienvenidos y no serán tolerados.
---
Directrices del [Manual de Recurse Center](https://www.recurse.com/manual). Gracias por la publicación, Recurse.
# Instalación de Haskell
## Use la herramienta Stack para empezar con Haskell
Instale [Stack](https://haskellstack.org) para tener el GHC (Glasgow Haskell Compiler) listo y para compilar sus proyectos.
En el caso de que usted no conozca nada sobre Stack y le gustaria tener una visión general, hay un [tutorial en vídeo sobre Stack](https://www.youtube.com/watch?v=sRonIB8ZStw).
## NO INSTALE "HASKELL PLATFORM"
En lugar de utilizar las instrucciones disponibles en Haskell.org, utilize Stack.
### ¿Por qué no utilizar "Haskell Platform"?
https://mail.haskell.org/pipermail/haskell-community/2015-September/000014.html
# ¿Cómo debería aprender Haskell?
La recomendación principal es leer las clases y completar todos los ejercicios de la versión 13 de cis1940 seguidos por el curso FP. Los links de ambos se encuentran abajo. Todo lo demas puede ser considerado opcional y es mencionado para que así sepas donde mirar.
## Curso cis1940 de Yorgey
> *Haz esto primero*, esta es la vía principal que recomendamos al ser introducido a Haskell.
Disponible [online](https://www.seas.upenn.edu/~cis1940/spring13/lectures.html).
[Brent Yorgey](https://byorgey.wordpress.com) Este curso es el mejor que he encontrado hasta ahora. Este curso es valioso ya que no te equipara para escribir Haskell basico, sino que ademas te ayudara a entender combinatoria.
La unica razón por la que no deberías empezar con cis1940 es si no eres un programador o eres uno con poca experiencia. Si ese es el caso, empieza con [El libro de Thompson (ingles)](https://www.haskellcraft.com/craft3e/Home.html) y haz la transición a cis1940.
---
## Curso FP
> Este es el curso que recomendamos hacer despues del curso cis1940 de Yorgey.
Disponible en github [aquí](https://github.com/bitemyapp/fp-course).
Esto reforzara y te dara experiencia implementando directamente las abstracciones introducidas en cis1940, esto es practica que es *critica* para estar cada vez mas comodo con el uso diario de Functor/Aplicativo/Monada/etc en Haskell. Realizando cis1940 y luego el curso FP es la recomendación principal de mi guia y es como enseñamos Haskell a cualquier persona.
---
## Curso suplementario despues de los cursos cis1940 y FP
> Proporciona mas material en temas intermediarios
cs240h esta disponible [en linea](http://www.scs.stanford.edu/14sp-cs240h/).
Este es el curso online de [Bryan O'Sullivan](https://github.com/bos) de la clase que el enseña en Stanford. Si no sabes quien es el, dale un vistazo a la mitad de las librerías que cualquier aplicación de Haskell necesita y veras su nombre en estas.Si ya haz hecho el curso de Yorgey te interesara particularmente los modulos de tipos fantasma, control de flujo de información, extensión del lenguaje, concurrencia, pipes, y lenses.
---
# Recursos para temas especificos en Haskell
Estos recursos no han sido investigados o probados con aprendices como los cursos cis1940 y FPT, pero estan listados en [la lista de temas](specific_topics.md) para que así tengas ideas de donde empezar.Esto incluye cosas como conceptos y temas intermedios/avanzados, por ejemplo herramientas y editores de texto.
## Dialogos
> Alojado en este repositorio [Aquí](dialogues.md).
Estos son de hecho muy importantes y de gran ayuda. Da un vistazo a estos para inmersiones profundas en una variedad de temas.
================================================
FILE: guide-fr.md
================================================
# Le Guide
Ceci est ma façon recommandée d'apprendre Haskell.
#### Quelque chose à garder en tête: *ne bloquez pas sur les points que vous ne comprenez pas immédiatement*. Continuez à avancer.
## Communauté
Notre canal IRC est `#haskell-beginners` sur Freenode.
Un client web IRC [ici](http://webchat.freenode.net/).
Les [listes de diffusion](https://wiki.haskell.org/Mailing_lists) Haskell.
### Règles d'usage de la communauté
[Voir le post sur l'enseignement de Chris Done](http://chrisdone.com/posts/teaching)
Soyez gentils et courtois. Etre méchant ou désagréable fait peur aux autres et ne les encourage pas à participer.
Une critique pour le plaisir de critiquer ne sert que la personne qui la fait, pas celle qui la reçoit.
Ne décrivez pas quelque chose comme "facile" ou "trivial". Vous créeriez un malaise chez ceux qui doivent travailler plus durement pour progresser. Les personnes qui apprennent lentement sont souvent celles qui font un apprentissage plus approfondi, c'est quelque chose que nous devons célébrer et encourager !
Ne pas feindre la surprise. N'ayez pas l'air surpris lorsque quelqu'un affirme ne pas savoir quelque chose. La personne se sentira mal et vous n'aurez rien accompli mis à part flatter votre égo.
Pas de "en fait…". Lorsqu'une personne dit quelque chose de presque - mais pas entièrement - correct, et vous répondez, "Ouais… en fait…" puis les corrigez. C'est particulièrement gênant lorsque la correction n'a aucune incidence sur la conversation actuelle. Cela ne signifie pas que Recurse Center ne se soucie pas de la recherche de la vérité ou que nous ne nous soucions pas d'être précis. Presque tous les "Ouais… en fait…" sont un moyen de se mettre en valeur, et non de la recherche de la vérité.
Pas de conduite accompagnée. Si vous voyez des personnes buter sur un problème, vous ne devez pas immédiatement donner des conseils. Laissez travailler dessus à moins que quelqu'un demande de l'aide. Eviter les interruptions est [un des objectifs fondateurs du canal #haskell-beginners](http://chrisdone.com/posts/teaching).
Pas de -ismes. Racisme, sexisme, homophobie, transphobie, et autres biais ne sont pas bienvenus et ne seront pas tolérés.
---
Recommandations du [manuel de the Recurse Center](https://www.recurse.com/manual). Merci de l'avoir publié Recurse Center.
# Qu'est ce que Haskell, GHC, et Cabal?
Haskell est un langage de programmation, défini par une spécification, la plus récente datant de 2010. Celle-ci est disponible [en ligne](http://www.haskell.org/onlinereport/haskell2010/).
## GHC
[GHC](http://www.haskell.org/ghc/) est le moyen le plus populaire de travailler avec le langage Haskell. Il inclut un compilateur, un REPL (interpréteur), la gestion de paquets, et plus encore.
## Cabal
[Cabal](https://www.haskell.org/cabal/download.html) s'occupe de la gestion du projet et de la résolution des dépendances. C'est lui qui aide à l'installation de projets, typiquement dans leurs propres bac à sable.
Cabal est l'équivalent de Bundler pour Ruby, de pip pour Python, de NPM pour Node, Maven, etc. GHC gère le packaging lui-même, Cabal choisit quelles versions doivent être installées.
# Mise en place
## Ubuntu
[Ce PPA](http://launchpad.net/~hvr/+archive/ghc) est excellent. C'est ce que j'utilise sur toutes mes machines Linux dédiées au développement.
Plus précisément:
```bash
$ sudo apt-get update
$ sudo apt-get install python-software-properties # v12.04 and below
$ sudo apt-get install software-properties-common # v12.10 and above
$ sudo add-apt-repository -y ppa:hvr/ghc
$ sudo apt-get update
$ sudo apt-get install cabal-install-1.20 ghc-7.8.3 happy-1.19.4 alex-3.1.3
```
Après, ajoutez ce qui suit à votre `$PATH` (bash\_profile, zshrc, bashrc, etc.) :
```
~/.cabal/bin:/opt/cabal/1.20/bin:/opt/ghc/7.8.3/bin:/opt/happy/1.19.4/bin:/opt/alex/3.1.3/bin
```
*Optionnel:* Vous pouvez aussi ajouter `.cabal-sandbox/bin` à votre _path_.
Ainsi, vous aurez accès au code que vous serez en train de développer directement
en ligne de commandes. Cela ne marchera que si votre répertoire de travail actuel
contient un _bac à sable_ cabal.
## Debian
### Utiliser le PPA d'Ubuntu
Si vous n'utilisez pas la version stable, vous pouvez suivre les mêmes étapes
que pour Ubuntu mais vous aurez besoin d'exécuter un commande supplémentaire.
Immédiatement après l'exécution de `sudo add-apt-repository -y ppa:hvr/ghc`,
lancez:
```bash
$ sudo sed -i s/jessie/trusty/g /etc/apt/sources.list.d/hvr-ghc-jessie.list
```
Pour les autres versions de Debian, il suffit de remplacer les occurrences de
`jessie` par le nom de votre version dans la commandes ci-dessus.
Si, pour une raison quelconque, le fichier
`/etc/apt/sources.list.d/hvr-ghc-jessie.list` n'existe pas, alors
`/etc/apt/sources.list` devrait contenir une ligne de ce genre:
deb http://ppa.launchpad.net/hvr/ghc/ubuntu jessie main
Remplacez alors `jessie` par `trusty` dans cette ligne.
### Compilation depuis les sources
Vous pouvez suivre
[ce guide](http://www.davesquared.net/2014/05/platformless-haskell.html)
écrit pour Mac OS X:
Notes:
- Configurez votre préfixe de manière adéquate lorsque vous configurez ghc.
- Au lieu de récupérer l'exécutable de `cabal-install`, récupérez les sources
et ensuite lancez le script `bootstrap.sh`.
## Fedora 21
Pour installer Haskell 7.8.4 depuis le dépôt non-officiel
(Fedora 22+ l'inclura dans l'officiel) :
```bash
$ sudo yum-config-manager --add-repo \
> https://copr.fedoraproject.org/coprs/petersen/ghc-7.8.4/repo/fedora-21/petersen-ghc-7.8.4-fedora-21.repo
$ sudo yum install ghc cabal-install
```
Comme indiqué dans
[la page copr petersen/ghc-7.8.4](https://copr.fedoraproject.org/coprs/petersen/ghc-7.8.4/)
cette version de ghc ne peut pas être installée en même temps que la version
Fedora/EPEL de ghc.
## Arch Linux
Pour installer Haskell depuis le dépôt officiel d'Arch Linux, lancez:
```bash
$ sudo pacman -S cabal-install ghc happy alex haskell-haddock-library
```
## Gentoo
Sur Gentoo, vous pouvez installer les différents composants de la plateforme
Haskell depuis Portage. Si vous utilisez `ACCEPT_KEYWORDS=arch` (par opposition à
`ACCEPT_KEYWORDS=~arch`), Portage installera d'anciennes versions des différents
composants Haskell. Maintenant que vous avez ça en tête, si et seulement si vous
utilisez `ACCEPT_KEYWORDS=arch`, ajoutez ce qui suit à
`/etc/portage/package.accept_keywords`.
dev-haskell/cabal-install ~arch
dev-lang/ghc ~arch
Une fois que cela est fait,
```bash
$ emerge -jav dev-lang/ghc dev-haskell/cabal-install
```
Gentoo garde une version "stable" (comprenez: vieille) de `cabal-install`
dans la hiérarchie de Portage. Donc vous allez devoir utiliser
`cabal-install` pour installer la dernière version. Notez que les backslashes
sont intentionnels dans ce qui suit.
```bash
$ \cabal update # Les backslashes
$ \cabal install cabal-install # sont intentionnels
```
Vous avez maintenant installé cabal au niveau global avec portage, et dans votre
répertoire personnel avec `cabal-install`. L'étape suivante est de s'assurer que
quand vous lancez `cabal` dans un terminal, votre shell lancera la version à jour
dans votre répertoire personnel. Vous allez donc devoir ajouter les lignes
suivantes à votre fichier de configuration du shell :
```bash
PATH=$PATH:$HOME/.cabal/bin
alias cabal="$HOME/.cabal/bin/cabal"
```
Si vous ne savez quel est votre shell, il y a de fortes chances que ce soit
Bash. Si vous utilisez Bash, le fichier à modifier est `~/.bashrc`. Si vous
utilisez Z-shell, il s'agit du fichier `~/.zshrc`. Vous pouvez lancer la commande
suivante pour savoir quel est votre shell :
```bash
echo $SHELL | xargs basename
```
J'utilise zsh, donc cette commande renvoie `zsh` quand je la lance.
Une fois que vous avez fait tout cela, vous allez devoir installer les outils
complémentaires `alex` et `happy`.
```bash
$ cabal install alex happy
```
Félicitations ! Vous avez maintenant une installation de Haskell en état de marche !
## Mac OS X
### 10.9
Installez l'app [GHC pour Mac OS X](http://ghcformacosx.github.io/) qui inclus
GHC et Cabal. Elle vous indiquera comment ajouter GHC et cabal à votre path
après que vous ayez déposé le `.app` quelque part.
### 10.6-10.8
Faites l'installation décrite ci-dessus avec cette [archive](https://www.haskell.org/platform/download/2014.2.0.0/ghc-7.8.3-x86_64-apple-darwin-r3.tar.bz2).
## Windows
- L'[installeur minimal pour GHC](http://neilmitchell.blogspot.com/2014/12/beta-testing-windows-minimal-ghc.html)
est capable de compiler `network` et les autres. Techniquement, il s'agit d'une
beta mais cela devrait répondre au besoin de quiconque lira ce guide.
N'oubliez pas de lancer l'installation en tant qu'administrateur puisque le
programme cherchera à s'installer dans votre répertoire Program Files.
## Utilisateurs d'autres versions de Linux
Téléchargez la dernière version des exécutables pour cabal et ghc
- [GHC](http://www.haskell.org/ghc/).
- [Cabal](https://www.haskell.org/cabal/download.html).
# Cours de base
## Le cours cis1940 de Yorgey
> *Faites le en premier*, c'est la principale introduction à Haskell que je recommande.
Disponible [en ligne](https://www.seas.upenn.edu/~cis1940/spring13/lectures.html).
Le cours de [Brent Yorgey](https://byorgey.wordpress.com) est le meilleur que j'ai trouvé jusque là.
Ce cours vous donnera les bases pour écrire du code en Haskell mais vous
aidera aussi à comprendre les combinateurs d'analyse (parser combinators).
La seule raison pour laquelle vous ne devriez pas commencer avec cis1940 est si vous n'êtes pas un
développeur ou inexpérimenté. Si c'est le cas, commencez par le
[livre de Thompson](https://www.haskellcraft.com/craft3e/Home.html) puis enchainez avec cis1940.
---
## Le cours FP
> C'est le cours que je recommande après avoir suivi le cours cis1940 de Yorgey
Disponible sur github [ici](https://github.com/bitemyapp/fp-course).
Ce cours va renforcer vos connaissances et vous fera acquérir de l'experience en
implémentant directement les abstractions introduites dans le cis1940, c'est un
exercice *capital* pour être à l'aise avec les usages habituels des
Functors/Applicatives/Monades/etc. en Haskell. Suivre les cours cis1940 puis
FP est la recommendation principale de mon guide et c'est comme ca que
j'enseigne Haskell à tout le monde.
---
## Cours supplémentaire cs240h
> Fournit plus de matière sur des sujets intermédiaires
Disponible [en ligne](http://www.scs.stanford.edu/14sp-cs240h/).
C'est la version en ligne du cours de [Bryan O'Sullivan](https://github.com/bos)
enseigné à Stanford. Si vous ne savez qui il est, jetez un coup d'oeil à la moitié
des libraries utilisées par les applications Haskell, son nom y figure. À regarder de
plus près, si vous avez déjà fait le cours de Yorgey, les modules sur les
types fantômes, les contrôles des flux d'informations, les extensions de language,
la concurrence, les pipes, et les lenses.
---
### Que sont les sucres syntactiques `<-` / `do` / comprehension de listes ?
Un [article](http://www.haskellforall.com/2014/10/how-to-desugar-haskell-code.html) excellent.
### Pour comprendre list et fold
- [Comprendre List et Folds](http://vimeo.com/64673035)
### Pour apprendre quelques typeclasses courantes
Utile pour comprendre `Functor`, `Applicative`, `Monad`, `Monoid` et autres
typeclasses en général mais aussi un peu de théorie des catégories spécifique
à Hask:
- La [Typeclassopedia](http://www.haskell.org/haskellwiki/Typeclassopedia)
### Comprendre les messages d'erreur standards d'Haskell
- [Comprendre les messages d'erreur standards](http://ics.p.lodz.pl/~stolarek/_media/pl:research:stolarek_understanding_basic_haskell_error_messages.pdf)
---
# Evaluation stricte et paresseuse, _guarded recursion_
- Le [livre](http://chimera.labs.oreilly.com/books/1230000000929/ch02.html)
écrit par Marlow au sujet du parallélisme et de la concurrence est une des
meilleures introduction au sujet de l'évaluation paresseuse et des formes
normales que j'ai trouvé. N'hésitez pas à utiliser d'autres ressources si
vous n'accrochez pas immédiatement à celle ci.
- [Des points en plus pour l'evaluation paresseuse](http://augustss.blogspot.hu/2011/05/more-points-for-lazy-evaluation-in.html)
- [Oh ma paresse !](http://alpmestan.com/posts/2013-10-02-oh-my-laziness.html)
- Question sur SO : '[Haskell a-t-il une évaluation paresseuse ?](https://stackoverflow.com/questions/13042353/does-haskell-have-tail-recursive-optimization)'
- les slides de [Johan Tibell](https://github.com/tibbe) tirés d'une présentation
intitulée [raisonner avec l'évaluation paresseuse](http://www.slideshare.net/tibbe/reasoning-about-laziness).
## Brève démonstration
```haskell
let a = 1 : a -- guarded recursion, (:) est évalué paresseusement
let (v : _) = a -- et on peut lui appliquer du pattern matching
> v
1
> head a -- head a == v
1
let a = 1 * a -- not guarded, (*) is strict
> a
*** Exception: <<loop>>
```
# IO
- [Ordre d'évaluation et jetons d'états](https://www.fpcomplete.com/user/snoyberg/general-haskell/advanced/evaluation-order-and-state-tokens)
- [Révéler les mystères de la monade IO](http://blog.ezyang.com/2011/05/unraveling-the-mystery-of-the-io-monad/).
- ["instructions" du premier ordre](http://blog.jle.im/entry/first-class-statements).
- [Haddocks pour System.IO.Unsafe.unsafePerformIO](http://hackage.haskell.org/package/base-4.7.0.1/docs/System-IO-Unsafe.html#v:unsafePerformIO)
Lisez la documentation et remarquez l'implémentation de `unsafeDupablePerformIO`
Commentaire sur un fil Reddit de `glaebhoerl` :
> Une intéressante note annexe: GHC a besoin de cacher la représentation du
> jeton d'état derrière un type abstrait IO car le jeton d'état doit toujours
> être utilisé linéairement (il ne doit pas être dupliqué ou abandonné), mais
> son système de types ne peut l'imposer. Clean, un autre langage paresseux
> à la Haskell, a des types uniques (qui sont des types linéaires et qui sont
> peut être différents sur d'autre points que j'ignore). Ils exposent le passage
> du Monde explicitement et proposent une monade IO (non-abstraite) uniquement
> pour plus de commodités.
# Monades et transformateurs de monades
> Ne faites pas ça avant de comprendre les typeclasses, Monoid, Functor et
> Applicative !
Implémenter les monades de la librairie standard (List, Maybe, Cont, Error,
Reader, Writer, State) par vous-même afin de mieux les comprendre. Après, vous
pouvez peut-être écrire un interpréteur monadique pour un langage avec des petites
expressions en utilisant le papier sur les
[transformateurs de monades étape par étape](http://catamorph.de/documents/Transformers.pdf)
(mentionné dans la section "transformateurs de monades" ci-dessous).
Écrire plusieurs interpréteurs en changeant juste le Monde pour changer les
sémantiques peut aider à comprendre ce qui se passe.
De la même manière, ré-implémenter `Control.Monad`. Des fonctions comme `mapM`
ou `sequence` sont de bonnes opportunités pour s'entrainer à écrire du code
monadique.
Le cours du FP peut être utilisé comme un guide lors de ce processus,
guide qui vous demandera également d'écrire vos propres Applicatives.
Crédits:
- Commentaires de htmltyp et Crandom sur Reddit
[ici](https://www.reddit.com/r/haskell/comments/29eke6/basic_program_ideas_for_learning_about_monads/cik5aj6).
- Commentaire de jozefg
[ici](https://www.reddit.com/r/haskell/comments/29eke6/basic_program_ideas_for_learning_about_monads/cik5trg).
# Test, spécifications, tests de propriétés (tests par génération)
- Ce [tutoriel](https://github.com/kazu-yamamoto/unit-test-example/blob/master/markdown/en/tutorial.md)
de Kazu Yamamoto est fantastique.
- [Simple-Conduit](https://github.com/jwiegley/simple-conduit): Une bonne librairie simple pour apprendre comment le streaming d'IO fonctionne en général. Les connaissances acquises ici sont transférables à Pipes et Conduit.
# Parsing en Haskell
- [Tutoriel](https://github.com/JakeWheat/intro_to_parsing) sur les parser
combinators en Haskell utilisant Parsec.
- [Ecrivez votre propre micro-Parsec](http://olenhad.me/articles/monadic-parsers/)
## Parsing et génération de JSON
Aeson est la solution standard de parsing de [JSON](https://json.org) en haskell.
Disponible sur [hackage](https://hackage.haskell.org/package/aeson) et
[github](https://github.com/bos/aeson).
- [Parser du JSON avec Aeson](http://blog.raynes.me/blog/2012/11/27/easy-json-parsing-in-haskell-with-aeson/)
- [Aeson et les types personalisés](http://bitemyapp.com/posts/2014-04-11-aeson-and-user-created-types.html)
- [Parser des données non-deterministiques avec aeson et les types sum](http://bitemyapp.com/posts/2014-04-17-parsing-nondeterministic-data-with-aeson-and-sum-types.html)
- [tutoriel Aeson](https://www.fpcomplete.com/school/starting-with-haskell/libraries-and-frameworks/text-manipulation/json)
# Algorithmes de graphes et structures de données
- Le [package fgl](https://hackage.haskell.org/package/fgl) en particulier
le plus court chemin purement fonctionnel [algos](http://hackage.haskell.org/package/fgl-5.4.2.2/docs/Data-Graph-Inductive-Query-SP.html).
- [Graphes inductifs et Algorithmes de Graphes Fonctionnels](http://web.engr.oregonstate.edu/~erwig/papers/abstracts.html#JFP01).
- [FGL/Haskell - Une bibliothèque de Graphes Fonctionnels](http://web.engr.oregonstate.edu/~erwig/fgl/haskell/old/fgl0103.pdf).
- [source de Data.Graph extraite du package Containers](http://hackage.haskell.org/package/containers-0.5.5.1/docs/Data-Graph.html).
- Le [package graphs](https://hackage.haskell.org/package/graphs).
- [une question SO sur PHOAS](https://stackoverflow.com/questions/24369954/separate-positive-and-negative-occurrences-of-phoas-variables-in-presence-of-rec)
- [un article sur PHOAS](https://www.fpcomplete.com/user/edwardk/phoas).
- [Attacher le noeud](http://www.haskell.org/haskellwiki/Tying_the_Knot).
- [Hackage: dag](https://hackage.haskell.org/package/dag).
# Environment de développement
## Emacs
- [le tutoriel d'Alejandro Serras](https://github.com/serras/emacs-haskell-tutorial/blob/master/tutorial.md)
- [Mes dotfiles](https://github.com/bitemyapp/dotfiles/)
- [la config emacs de Chris Done](https://github.com/chrisdone/chrisdone-emacs)
## Vim
- [la page Vim sur haskellwiki](http://www.haskell.org/haskellwiki/Vim)
- [Haskell-vim-now](https://github.com/begriffs/haskell-vim-now)
- [GHC-Mod](https://github.com/kazu-yamamoto/ghc-mod)
- [plugin vim GHC-Mod](https://github.com/eagletmt/ghcmod-vim)
- [Hindent](https://github.com/chrisdone/hindent)
## Sublime Text
- [SublimeHaskell](https://github.com/SublimeHaskell/SublimeHaskell)
# Utilisation de Cabal
## Recommandations pour Cabal
L'enfer de Cabal était un problème pour les utilisateurs d'Haskell avant
l'introduction des bacs à sable. Une installation en dehors d'un bac à sable se
fera dans le package-db de l'utilisateur. Ce n'est *pas* une bonne idée mis à part
pour quelques librairies fondamentales comme Cabal, alex, et happy. Rien d'autre ne
devrait être installé dans le package-db de l'utilisateur ou le global à moins que
vous ne sachiez ce que vous faites.
Quelques bonnes pratiques pour éviter l'enfer de cabal sont disponibles
[ici](http://softwaresimply.blogspot.com/2014/07/haskell-best-practices-for-avoiding.html).
Pour faire des expérimentation avec un package ou démarrer un projet, commencez
par `cabal sandbox init` dans un nouveau dossier.
Pour résumer:
- Toujours utiliser des bacs à sable pour installer de nouveaux packages, créer des
projets, ou démarrer des experimentations
- Utiliser `cabal repl` pour démarrer une instance ghci dans un projet
L'approche basée sur les bacs à sable que je suggère permet d'éviter les problèmes
liés à la gestion des dépendances des packages, mais elle n'est pas compatible avec
les packages pré-construits fournis par Haskell Platform.
Si vous apprenez Haskell et ne comprenez pas comment ghc-pkg et Cabal fonctionnent,
*évitez platform* et utilisez les instructions préalables du guide à la place.
## Stackage
Pour les utilisateurs (de Yesod généralement) qui ont des problèmes de build, considérez Stackage.
- Un bon résumé de ce qu'est Stackage
[ici](https://www.fpcomplete.com/blog/2014/05/stackage-server).
L'auteur estime que Stackage est généralement plus utile que `cabal freeze`.
# Hoogle et Haddock
## Chercher du code à partir de la signature des types
Le [moteur de recherche Hoogle](http://www.haskell.org/hoogle/) permet des
recherches par type.
Par exemple, le résultat d'une recherche avec `(a -> b) -> [a] -> [b]`
sont disponibles [ici](http://www.haskell.org/hoogle/?hoogle=%28a+-%3E+b%29+-%3E+%5ba%5d+-%3E+%5bb%5d).
Hoogle est également hébergé par fpcomplete
[ici](https://www.fpcomplete.com/hoogle).
Il existe aussi [Hayoo](http://holumbus.fh-wedel.de/hayoo/hayoo.html) (qui
contient tout hackage par défaut).
## Mettre en place propre instance local de Hoogle
Vous pouvez regarder [ici](https://gist.github.com/bitemyapp/3e6a015760775e0679bf).
## Haddock
1. [Réparer votre documentation Hackage](http://fuuzetsu.co.uk/blog/posts/2014-01-06-Fix-your-Hackage-documentation.html)
2. [La v2 de la documentation de Hackage](http://fuuzetsu.co.uk/blog/posts/2014-01-06-Hackage-documentation-v2.html)
Notez que ces billets sont *légèrement obsolètes*: par exemple, Hackage contient
maintenant de nouvelles informations concernant la documentation et le statut
du build.
## Ce que vous avez vraiment besoin de savoir
Afin qu'Haddock inclue la documentation des paquets référencés, vous devez
mettre `documentation: True` dans votre `~/.cabal/config`. Si vous avez laissé la valeur
par défaut (`False`) ou l'avez délibérément définie comme `False`, vous devrez
supprimer tous vos paquets et les réinstaller avant de générer des haddocks.
Une autre chose que vous devez garder en tête est que comme le paramètre `$pkg`
est interprété *par* cabal, et non par vous, les paramètres `html-location` et
`content-location` *doivent être entourés de guillemets simples* et entrés dans
un shell ou contenus dans un script shell. Ils ne fonctionneront pas dans un Makefile,
car on pensera alors qu'il s'agit de variables pour Make.
```bash
#! /usr/bin/env sh
# Vous pouvez écrire ceci ligne par ligne en omettant les backslashes
cabal haddock --hoogle --hyperlink-source \
--html-location='http://hackage.haskell.org/package/$pkg/docs' \
--contents-location='http://hackage.haskell.org/package/$pkg'
```
# TravisCI
Si vous êtes comme moi un grand fan de [TravisCI](https://travis-ci.org), je
vous recommande alors *fortement* de jeter un oeil à
[multi-ghc-travis](https://github.com/hvr/multi-ghc-travis) pour avoir une base
de fichier `travis.yml` pour vos projets Haskell.
# Frontend/JavaScript
Nous avons des problèmes de riches ! Voilà les trois principaux choix que je
peux recommander:
* [Haste](http://haste-lang.org/) un compilateur de Haskell vers JavaScript
- Le [compilateur](https://github.com/valderman/haste-compiler) sur github.
- Une excellente
[démo](http://www.airpair.com/haskell/posts/haskell-tutorial-introduction-to-web-apps)
de Haste avec un exemple de projet.
* [GHCJS](https://github.com/ghcjs/ghcjs)
- [Introduction à GHCJS](http://weblog.luite.com/wordpress/?p=14)
- [Des interfaces web réactives avec GHCJS and Sodium](http://weblog.luite.com/wordpress/?p=127)
- [Écrire des extensions Atom en Haskell en utilisant ghcjs](http://edsko.net/2015/02/14/atom-haskell/)
* [PureScript](http://www.purescript.org/)
- Pas strictement du Haskell comme Haste and GHCJS, mais un choix populaire
chez les Haskellers.
- Écrit en et inspiré par Haskell.
- Essayez PureScript dans votre navigateur [ici](http://try.purescript.org/)
- Un très bon guide pour [démarrer](http://www.christopherbiscardi.com/2014/06/22/getting-started-with-purescript/)
## Quel langage frontend utiliser ?
GHCJS et Haste sont tous deux du pur Haskell. GHCJS marchera avec de plus
nombreux paquets Haskell que Haste, mais cela n'impacte pas un grand nombre
de projets frontend. PureScript n'est pas du tout du Haskell, donc un partage
direct du code avec votre backend ne fonctionnera pas.
GHCJS a le plus gros coût en terme de poids, avec environ 100ko (Luite
travaille sur ce point). Haste et PureScript sont compétitifs.
PureScript a la meilleure intégration dans la suite d'outils javascript (il
utilise gulp/grunt/bower), GHCJS et Haste s'intègrent mieux avec les outils
Haskell (Cabal).
Les trois sont de très bons choix et sont adaptés à la plupart des projets
frontend.
# Pour mieux comprendre l'évaluation paresseuse, NF, WHNF
- [Notes sur lambda-calcul](https://vec.io/posts/notes-on-lambda-calculus).
## Documents de recherche sur le lambda-calcul paresseux
- [La nécessité du lambda-calcul](http://homepages.inf.ed.ac.uk/wadler/topics/call-by-need.html#need-journal).
- [Démonstration de la réduction avec lambda-calcul](http://www.itu.dk/~sestoft/papers/sestoft-lamreduce.pdf)
- [Le lambda-calcul paresseux](http://www.cs.ox.ac.uk/files/293/lazy.pdf).
- [Evaluation paresseuse en Haskell](http://www.vex.net/~trebla/haskell/lazy.xhtml)
# Parallelisme / Concurrence
- [Programmation Parallele et Concurrente en Haskell](http://chimera.labs.oreilly.com/books/1230000000929)
Ce livre de Simon Marlow est probablement le meilleur que j'ai lu sur le sujet du parallélisme et de
la concurrence.
- Un [pas à pas](http://kukuruku.co/hub/haskell/haskell-testing-a-multithread-application) complet
sur les tests et le développement incrémental d'une application multi-threadée en Haskell.
- [Programmation Fonctionnelle Réactive](http://www.haskell.org/haskellwiki/Functional_Reactive_Programming)
# Lenses et Prisms
Une fois que êtes confortables avec Haskell, vous devriez considérer fortement l'apprentissage
des Lenses et Prisms, même en tant que simple "utilisateur". Vous n'avez pas besoin de comprendre
la catégorie sous-jascente pour que cela vous soit utile.
Les gens sur-estiment grandement la difficulté d'utiliser les Lens. Quiconque confortable
avec Functor/Foldable/Traversable (ou juste le premier) peux utiliser les
lenses et prisms et se simplifier la vie.
Si vous avez déjà fait quelque chose comme: `(fmap . fmap)` vous étiez en train de "lenser" dans votre tête.
Je recommande ces deux tutoriels / introductions:
- [Un petit tutoriel sur Lens pour commencer](https://www.fpcomplete.com/school/to-infinity-and-beyond/pick-of-the-week/a-little-lens-starter-tutorial)
- [Lens: Lenses, Folds et Traversals](https://github.com/ekmett/lens#lens-lenses-folds-and-traversals)
Regardez ici pour plus d'informations: [Lens package on hackage](http://hackage.haskell.org/package/lens).
# Schémas de récursion
Certains des mots en \*-morphisme dont vous avez entendu parler jusque là renvoient à la
récursion. NB - avant de vous attaquer à la suite vous devriez savoir comment implementer
foldr pour des listes et au moins une autre structure de données, comme les arbres. (les folds
sont des catamorphismes) Savoir comment implementer un unfold (anamorphisme) pour les même structures
devrait clarifier un peu les choses.
Ces documents se limitent aux traversables et foldables.
- [Une introduction aux schémas de récursion](http://patrickthomson.ghost.io/an-introduction-to-recursion-schemes/)
- [N'ayez pas peur du chat](http://fho.f12n.de/posts/2014-05-07-dont-fear-the-cat.html) (un jeu de mot entre "cat" (chat) et le prefixe cata) -
Une bonne démonstration sur comment l'hylomorphisme est une composition de cata et ana.
- [Schémas de Récursion](http://comonad.com/reader/2009/recursion-schemes/) - Ce
guide pratique est excellent.
- [Programmation Fonctionnelle avec des Bananes, des Lenses, des Enveloppes et du Fil barbelé](http://eprints.eemcs.utwente.nl/7281/01/db-utwente-40501F46.pdf)
- [Catamorphismes](https://www.fpcomplete.com/user/edwardk/recursion-schemes/catamorphisms)
# GHC Core et tuning de performance
- [Ecrire du Haskell aussi rapide que du C](write_haskell_as_fast_as_c.md)
- [GHC Wiki: le Type CoreSyn](https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/CoreSynType).
- [Hackage: GHC Core](https://hackage.haskell.org/package/ghc-core).
- [Question sur SO: Lire GHC Core](https://stackoverflow.com/questions/6121146/reading-ghc-core).
- [Haskell aussi rapide que du C](http://donsbot.wordpress.com/2008/06/04/haskell-as-fast-as-c-working-at-a-high-altitude-for-low-level-performance/).
- [Real World Haskell, Chapitre 25: Profilage and Optimisations](http://book.realworldhaskell.org/read/profiling-and-optimization.html).
# Type et Théorie des Catégories
> *Pas* nécessaire pour écrire du Haskell, juste pour ceux intéressés !
Si vous voulez en apprendre plus sur les types et la théorie des catégories:
- [Le guide de Catster](http://byorgey.wordpress.com/2014/01/14/catsters-guide/) et
[Le guide de Catster 2](http://byorgey.wordpress.com/catsters-guide-2/)
- Le [wikibook haskell](http://en.wikibooks.org/wiki/Haskell/Category_theory)
a de beaux diagrammes.
- [Théorie des Catégories](http://www.haskell.org/haskellwiki/Category_theory) sur
haskellwiki, dispose de bons liens vers d'autres ressources.
- [Categories à partir de rien](http://science.raphael.poss.name/categories-from-scratch.html), inclus des exemples concrets.
- La liste [Superbes travaux sur les languages de programmation](http://www.cis.upenn.edu/~bcpierce/courses/670Fall04/GreatWorksInPL.shtml) de Pierce.
## Livres
- [Question sur Quora: Quel est le meilleur livre sur la théorie des catégories ?](http://www.quora.com/Category-Theory/What-is-the-best-textbook-for-Category-theory?share=1) les recommandations de Kmett
- [Awodey](http://ukcatalogue.oup.com/product/9780199237180.do) et
[MacLane](http://www.amazon.com/Categories-Working-Mathematician-Graduate-Mathematics/dp/0387984038). Les livres de référence sur la théorie des catégories.
- [Fondations Pratiques pour les Languages de Programmation de Harper](http://www.cs.cmu.edu/~rwh/plbook/book.pdf) est la meilleure introduction à la théorie des catégories d'un point de vue des languages de programmation.
- [La théorie des Types et la Programmation Functionnelle](http://www.cs.kent.ac.uk/people/staff/sjt/TTFP/).
# Autres sujets amusants
## Paramétricité, ad-hoc vs. polymorphisme paramétrique, théorèmes libres
- [Paramétricité](tony_parametricity.pdf).
- [Les sources TeX](https://github.com/tonymorris/parametricity/) du
talk ci-dessus.
- [Rendre le polymorphisme ad-hoc moins ad-hoc](http://swizec.com/blog/week-20-making-ad-hoc-polymorphism-less-ad-hoc/swizec/6564).
- [Théorèmes gratuits !](http://ttic.uchicago.edu/~dreyer/course/papers/wadler.pdf).
## Initial et Final, les DSL, Finally Tagless
- [Encodages finaux, Partie 1: Une Démonstration rapide](http://creativelad.wordpress.com/2013/11/28/final-encodings-part-1-a-quick-demonstration/).
- [Transformer des valeurs Polymorphiques](http://martijn.van.steenbergen.nl/journal/2009/10/18/transforming-polymorphic-values/).
- [Les GADT en Haskell 98](http://martijn.van.steenbergen.nl/journal/2009/11/12/gadts-in-haskell-98/).
- [Lambda-calcul linéaire Typed Tagless-Final](https://www.fpcomplete.com/user/mutjida/typed-tagless-final-linear-lambda-calculus).
- [Interprétations de Typed tagless-final: notes de Lecture](http://okmij.org/ftp/tagless-final/course/course.html).
- [Les interpréteurs Typed Tagless Final](http://okmij.org/ftp/tagless-final/course/lecture.pdf).
- [Le chien qui n'aboyait pas](http://existentialtype.wordpress.com/2011/03/21/the-dog-that-didnt-bark/) moins spécifique mais intéressant tout de même.
## Co-monades
- [Co-monades en Haskell](https://speakerdeck.com/dmoverton/comonads-in-haskell).
- [question sur SO: Est-ce qu'une monade peut être une co-monade ?](https://stackoverflow.com/questions/16551734/can-a-monad-be-a-comonad).
## Yoneda / Co-Yoneda
- [question sur SO: explication pas-à-pas de co-yoneda](https://stackoverflow.com/questions/24000465/step-by-step-deep-explain-the-power-of-coyoneda-preferably-in-scala-throu).
- Free monads for Less, une séquence de trois articles par Edward Kmett
* [Partie 1: Co-densité](http://comonad.com/reader/2011/free-monads-for-less/).
* [Partie 2: Yoneda](http://comonad.com/reader/2011/free-monads-for-less-2/).
* [Partie 3: Yielding IO](http://comonad.com/reader/2011/free-monads-for-less-3/).
## Propositions vs. Jugements (informatique)
- [une question sur StackExchange: Quelle est la difference entre les propositions et les jugements ?](http://cstheory.stackexchange.com/questions/9826/what-is-the-difference-between-propositions-and-judgments).
- [Notes de lecture d'un petit cours de trois lectures](http://www.ae-info.org/attach/User/Martin-L%C3%B6f_Per/OtherInformation/article.pdf)
# Typage Dépendent
- [Intégrer les type sum, les value constructors, et les type constructors](http://bitemyapp.com/posts/2014-04-05-grokking-sums-and-constructors.html).
- [Programmation légère avec typage dépendant](http://okmij.org/ftp/Computation/lightweight-dependent-typing.html).
- [Le language de programmation Idris](http://www.idris-lang.org/).
# Interconnexion de binaires statique
- [Interconnexion statique](https://wiki.haskell.org/Web/Literature/Static_linking)
- [Interconnexion statique avec GHC sur Arch Linux](http://www.edofic.com/posts/2014-05-03-ghc-arch-static.html)
- [Interconnexion statique de binaires Linux pour ARM & MIPS](https://stackoverflow.com/questions/14270177/ghc-statically-linking-linux-binaries-for-arm-mips-processors)
- [Interconnexion statique GMP avec GHC et LLVM](https://stackoverflow.com/questions/10539857/statically-link-gmp-to-an-haskell-application-using-ghc-llvm)
## Dialogues
> Hébergés dans un dépôt [ici](dialogues.md).
Ils sont importants et utiles. A regarder pour une compréhension approfondie sur
des sujets variés.
================================================
FILE: guide-hr.md
================================================
# Kako naučiti Haskell
Ovo je preporučeni put za učenje Haskella zasnovan na iskustvu u pomaganju drugim ljudima. Ovo je lista preporuka jednog od autora [Haskell knjige](https://haskellbook.com)
## Za one koji ne govore Hrvatski
- [In English](README.md)
- [Auf Deutsch](guide-de.md)
- [En Español](guide-es.md)
- [En Français](guide-fr.md)
- [Bahasa Indonesia](guide-id.md)
- [In Italiano](guide-it.md)
- [日本語](guide-ja.md)
- [한국어](guide-ko.md)
- [Em Português](guide-pt.md)
- [În Română](guide-ro.md)
- [По-русски](guide-ru.md)
- [Srpski](guide-sr.md)
- [Sa Tagalog](guide-tl.md)
- [Türkçe](guide-tr.md)
- [Українською](guide-ua.md)
- [简体中文](guide-zh_CN.md)
- [繁體中文](guide-zh_tw.md)
#### *Ne obraćajte mnogo pažnje na stvari koje iz prve ne razumijete*. Samo idite naprijed!
## Zajednica
Naš IRC kanal je `#haskell-beginners` na Freenodeu.
IRC web [klijent](http://webchat.freenode.net/).
Haskell [email lista](https://wiki.haskell.org/Mailing_lists).
### Smjernice zajednice
Pogledajte [smjernice zajednice](coc.md) da bi razumjeli kakvo ponašanje se očekuje na IRC kanalu. Bit ćete upozoreni ako očigledno "trolate" , ali budite svjesni toga da kanal služi isključivo onima koji uče ili podučavaju Haskell.
# Instaliranje Haskella
## Koristite Stack da biste krenuli sa Haskellom
Preuzmite [Stack](https://haskellstack.org) da bi uz pomoć njega instalirali GHC za gradnju projekata.
Ako ne znate ništa o Stacku a željeli biste saznati, pogledajte ovaj [Stack video tutorial](https://www.youtube.com/watch?v=sRonIB8ZStw).
## Također, NEMOJTE INSTALIRATI HASKELL PLATFORMU
Umjesto da pratite uputstva sa Haskell.org instalirajte Stack.
### Zašto ne platforma ?
https://mail.haskell.org/pipermail/haskell-community/2015-September/000014.html
# Kako da naučim Haskell?
Glavna preporuka je da pročitate lekcije i završite sve vježbe iz Spring 13 verzije cis1940 tečaja nakon kojega ide FP tečaj. Oba linka su ispod. Sve ostalo može se smatrati opcionalnim i spomenuto je ovdje da biste znali gdje da tražite resurse.
## Alternativno...
[@dmvianna](https://github.com/dmvianna) je željela da napomenem da su ovo samo besplatni i preporučeni resursi, ako ste zainteresirani da pogledate knjigu preporučujemo od sveg srca našu [Haskell Knjigu!](https://haskellbook.com) Ova knjiga zamjenjuje sve spomenuto.
## Yorgeyjev cis1940 tečaj
> *Pročitajte ovo prvo*, ovo je primarni način koji preporučujemo za upoznavanje sa Haskellom
Dostupno [online](https://www.seas.upenn.edu/~cis1940/spring13/lectures.html).
[Brent Yorgey](https://byorgey.wordpress.com)jev tečaj je najbolji tečaj koji sam vidio do sada. Ovaj tečaj je vrijedan zato što ne samo da će Vas pripremiti da pišete osnovni Haskell već će Vam i pomoći da razumijete parser kombinatore.
Jedini razlog da ne počnete sa cis1940 tečajem je ako niste programer ili ste programer sa malo iskustva.
U tom slučaju počnite sa [Thompsonovom knjigom](https://www.haskellcraft.com/craft3e/Home.html) i nakon nje prijeđite na cis1940.
---
## FP tečaj
> Ovo je tečaj koji preporučujemo nakon Yorgeyjevog cis1940 tečaja
Dostupan je na [githubu](https://github.com/bitemyapp/fp-course).
On će utvrditi iskustvo u direktnom implementiranju apstrakcija koje
su uvedene u cis1940 tečaju. Ovo je praksa koja je *kritična* da bi se osjećali
ugodno sa svakodnevnom upotrebom Fanktora/Aplikativa/Monada itd. u Haskellu.
Glavna preporuka ovog vodiča je da prijeđete cis1940 a zatim FP tečaj i to je način
na koji učimo Haskell sve zainteresirane.
---
## Dodatni tečaj nakon cis1940 i FP
> Sadrži više materijala o srednje naprednim temama
cs240h je dostupan [online](http://www.scs.stanford.edu/14sp-cs240h/).
Ovo je [Bryan O'Sullivan](https://github.com/bos)ov online tečaj kojim on predaje na
Stanfordu. Ako ne znate tko je on bacite oko i vidjet ćete da je njegovo ime na pola Haskell
biblioteka koje su potrebne bilo kojem Haskell programu.
Naročito treba spomenuti, ako ste već završili Yorgeyjev tečaj,
module sa fantomskim tipovima, kontrola toka informacija, ekstenzije jezika, konkurentnost,
pipes i lenses biblioteke.
---
# Resursi za specifične teme u Haskellu
Ovi resursi nisu testirani sa učenicima kao što su tečajevi cis1940 i FP ali se nalaze u [listingu tema](specific_topics.md) tako da imate ideju odakle krenuti. Ovo uključuje srednje/napredne koncepte i teme kao što su alati i tekst editori.
## Dijalozi
> Nalaze se u ovom [repozitoriju](dialogues.md).
Ovo je naročito važno i korisno. Ovo je dublji pregled različitih tema.
================================================
FILE: guide-id.md
================================================
# Bagaimana cara belajar Haskell
Ini adalah langkah yang direkomendasikan untuk belajar Haskell berdasarkan pengalaman membantu orang lain. Daftar rekomendasi bersumber dari salah satu penulis [Haskell Book.](http://haskellbook.com)
## Untuk pembicara non-English
- [In English](README.md)
- [Auf Deutsch](guide-de.md)
- [En Español](guide-es.md)
- [En Français](guide-fr.md)
- [Na Hrvatskom](guide-hr.md)
- [In Italiano](guide-it.md)
- [日本語](guide-ja.md)
- [한국어](guide-ko.md)
- [Em Português](guide-pt.md)
- [În Română](guide-ro.md)
- [По-русски](guide-ru.md)
- [Srpski](guide-sr.md)
- [Sa Tagalog](guide-tl.md)
- [Türkçe](guide-tr.md)
- [Українською](guide-ua.md)
- [简体中文](guide-zh_CN.md)
- [繁體中文](guide-zh_tw.md)
#### *Jangan memikirkan hal yang tidak langsung anda mengerti*. Lanjutkan terus!
## Komunitas
Kanal IRC kami adalah `#haskell-beginners` di Freenode.
Situs klien IRC [disini](http://webchat.freenode.net/).
Haskell [milis](https://wiki.haskell.org/Mailing_lists).
### Panduan Komunitas
Lihat [Panduak Komunitas](coc.md) untuk mengerti etika yang diharapkan ketika berada pada kanal IRC. Anda akan mendapatkan peringatan jika Anda melakukan hasutan yang tidak jelas, namun perlu menjadi perhatian bahwa kanal secara eksklusif untuk siapa yang belajar atau mengajarkan Haskell.
# Memasang Haskell
## Gunakan Stack untuk melanjutkan dengan Haskell
Dapatkan [Stack](https://haskellstack.org) untuk mendapatkan GHC terpasang dan membuat proyek anda.
Jika Anda tidak tau apapun tentang Stack dan ingin sebuah ikhtisar, periksa ini [Video pengajaran Stack komprehensif](https://www.youtube.com/watch?v=sRonIB8ZStw).
## Dan juga, JANGAN PASANG HASKELL PLATFORM
Sebagai ganti mengikuti instruksi pada Haskell.org, dapatkan Stack.
### Mengapa bukan platform?
https://mail.haskell.org/pipermail/haskell-community/2015-September/000014.html
# Bagaimana seharusnya Saya mempelajari Haskell?
Yang paling direkomendasikan adalah untuk membaca materi kuliah dan menyelesaikan seluruh latihan/pekerjaan rumah untuk versi Spring 13 dari cis1940 diikuti dengan pelajaran FP. Keduanya ditautkan dibawah. Selain dari itu dapat dikategorikan sebagai opsional dan diberitahukan agar anda mengetahui kemana harus mencarinya.
## Haskell Programming from First Principles
[@dmvianna](https://github.com/dmvianna) menginginkan saya untuk memberitahu bahwa dibawah ini adalah rekomendasi sumber yang _gratis_. Jika anda ingin memiliki buku, kami sangat merekomendasikan buku kami [Haskell Book!](http://haskellbook.com). Jika kamu tidak mampu membeli bukunya karena alasan apapun, silahkan hubungi kami dengan surat elektronik menggunakan kontak di [our support page](http://haskellbook.com/support.html).
## Kursus cis1940 Yorgey
> *Lakukan ini terlebih dahulu*, ini adalah langkah awal yang kami rekomendasikan untuk dikenalkan kepada
> Haskell.
Tersedia [online](https://www.seas.upenn.edu/~cis1940/spring13/lectures.html).
Mata kuliah [Brent Yorgey](https://byorgey.wordpress.com) adalah yang terbaik yang saya temukan sejauh ini.
Mata kuliah ini berharga karena tidak hanya membekali anda untuk menulis dasar
Haskell namun juga membantu anda untuk mengerti parser combinators.
Satu-satunya alasan anda tidak seharusnya mulai dengan cis1940 adalah jika anda bukanlah programmer
atau adalah yang tidak berpengalaman. Jika demikian, mulailah dengan
[Thompson's book](https://www.haskellcraft.com/craft3e/Home.html) kemudian beralih
ke cis1940.
---
## Pelajaran FP
> Ini adalah pelajaran yang kami rekomendasikan untuk dikerjakan setelah mata kuliah cis1940 Yorgey.
Tersedia di github [disini](https://github.com/bitemyapp/fp-course).
Ini akan membantu dan memberikan anda pengalaman secara langsung mengimplementasikan
abstraksi yang dikenalkan di cis1940, ini adalah latihan yang _penting_ untuk
menjadi nyaman dengan penggunaan Functor/Applicative/Monad/dll sehari-hari pada
Haskell. Menempuh cis1940 dan kemudian pelajaran FP mewakili rekomendasi utama
dari panduan saya dan bagaimana kami mengajarkan Haskell kepada semua orang.
---
## Pelajaran tambahan setelah pelajaran cis1940 dan FP
> Menyediakan materi tambahan untuk topik menengah.
cs240h tersedia secara online:
- [Spring 14](http://www.scs.stanford.edu/14sp-cs240h/)
- [Winter 16](http://www.scs.stanford.edu/16wi-cs240h/)
Ini adalah pelajaran online [Bryan O'Sullivan](https://github.com/bos) dari kelas
yang ia ajar di Stanford. Jika anda tidak mengetahui siapa ia, coba lihat sebentar pada setengah
pustaka setiap aplikasi Haskell yang dibutuhkan dan namanya ada pada pustaka tersebut. Dengan
catatan tersendiri bahwa anda telah menyelesaikan pelajaran Yorgey yang ada di modul
phantom types, information flow control, language extensions, concurrency,
pipes, dan lenses.
---
# Sumber untuk topik spesifik pada Haskell
Sumber-sumber ini tidak diperiksa atau dicoba kepada pelajar seperti pelajaran cis1940 dan FP, tapi ditautkan pada [the topic listing](specific_topics.md) sehingga anda memiliki gambaran mengenai darimana harus memulai. Hal ini juga termasuk konsep menengah/lanjutan dan subyek seperti alat-alat dan editor teks.
## Dialog
> Di pasang pada repositori [disini](dialogues.md).
Ini sebenarnya lumayan penting dan membantu. Lihat kesini untuk mengenal lebih dalam pada beberapa
variasi topik.
================================================
FILE: guide-it.md
================================================
# La Guida
Questa è la strada che raccomando per imparare Haskell.
## Per chi non parla italiano
- [In English](README.md)
- [Auf Deutsch](guide-de.md)
- [En Español](guide-es.md)
- [En Français](guide-fr.md)
- [Na Hrvatskom](guide-hr.md)
- [Bahasa Indonesia](guide-id.md)
- [日本語](guide-ja.md)
- [한국어](guide-ko.md)
- [Em Português](guide-pt.md)
- [În Română](guide-ro.md)
- [По-русски](guide-ru.md)
- [Srpski](guide-sr.md)
- [Sa Tagalog](guide-tl.md)
- [Türkçe](guide-tr.md)
- [Українською](guide-ua.md)
- [简体中文](guide-zh_CN.md)
- [繁體中文](guide-zh_tw.md)
#### Un consiglio: *non preoccupatevi se non capite qualcosa alla prima lettura*. Andate avanti.
## Comunità
Il nostro canale IRC è `#haskell-beginners` su Freenode.
Un client web per IRC è disponibile [qui](http://webchat.freenode.net/).
La [mailing list](https://wiki.haskell.org/Mailing_lists) di Haskell.
### Linee guida per la comunità
[Leggete il post di Chris Done sull'insegnamento](http://chrisdone.com/posts/teaching).
Siate gentili e cortesi. Comportamenti crudeli o meschini spaventano gli altri e fanno passare la voglia di partecipare.
Crtitiche facili, in cui non mettete impegno, beneficiano soltanto voi e non la persona che le riceve.
Non descrivete niente con parole come "facile" o "banale". Chi legge si sentirà stupido perché le cose che definite come triviali possono aver richiesto molto impegno. Spesso chi impara lentamente impara più profondamente, è una cosa che dovremmo perseguire!
Non fate finta di essere sorpresi quando qualcuno vi dice che non sa qualcosa. Lo farete sentire soltanto stupido e non avrete ottenuto niente a parte sentirvi più furbi.
Non dite beh-in realtà. Come quando qualcuno dice che qualcosa è quasi, ma non completamente corretta, e voi cominciate a dire, "beh, in realtà…" e poi fate una piccola correzione. È molto irritante, specialmente quando la correzione non è pertinente alla conversazione che state avendo. Questo non significa che l'Hacker School non si preoccupi della verità o che non ci interessi essere precisi. Ma questi modi di fare sono quasi sempre più una questione di pavoneggiamento che altro.
Non dite agli altri cosa devono fare. Se qualcuno sta completando un esercizio non dovreste interromperlo continuamente con consigli. Lasciate che trovi la sua strada a meno che non lo chieda esplicitamente. Evitare interruzioni è [uno degli obiettivi fondamentali di #haskell-beginners](http://chrisdone.com/posts/teaching).
Non lasciate spazio a sottili "ismi". Razzismo, sessismo, omofobia, transfobia, e altri tipi di pregiudizi non saranno tollerati.
---
Linee guida tratte dal [manuale della Hacker School ](https://www.hackerschool.com/manual). Grazie per averle rese pubbliche.
# Cosa sono Haskell, GHC e Cabal?
Haskell è un linguaggio di programmazione, e come potete leggere nei report, la versione più recente è stata rilasciata nel 2010. Il report è disponibile online:
[report](http://www.haskell.org/onlinereport/haskell2010/).
## GHC
[GHC](http://www.haskell.org/ghc/) è il modo più classico per lavorare in Haskell. Include un compilatore, un REPL (interprete), un gestore automatico di pacchetti e librerie, ed altro.
## Cabal
[Cabal](https://www.haskell.org/cabal/download.html) è software per gestire i progetti haskell e risolvere le dipendenze. È lo strumento che vi permetterà di installare i pacchetti, tipicamente ciascuno nel proprio sandbox.
Cabal è equivalente a Bundler di Ruby, pip di Python, NPM di Node, Maven, etc. GHC
gestisce i pacchetti indipendentemente, Cabal sceglie quale versione installare.
# Il set-up dei tool
## Ubuntu
[Questo PPA](http://launchpad.net/~hvr/+archive/ghc) è ottimo ed è quello che uso su tutte le mie macchine linux, sia per i build automatici che per lo sviluppo.
Istruzioni specifiche:
```bash
$ sudo apt-get update
$ sudo apt-get install python-software-properties # v12.04 and below
$ sudo apt-get install software-properties-common # v12.10 and above
$ sudo add-apt-repository -y ppa:hvr/ghc
$ sudo apt-get update
$ sudo apt-get install cabal-install-1.20 ghc-7.8.3 happy-1.19.4 alex-3.1.3
```
Aggiungete poi la seguente linea al vostro `$PATH` (bash\_profile, zshrc, bashrc, etc):
```
~/.cabal/bin:/opt/cabal/1.20/bin:/opt/ghc/7.8.3/bin:/opt/happy/1.19.4/bin:/opt/alex/3.1.3/bin
```
*Opzionale:* Potete anche aggiungere `.cabal-sandbox/bin` al vostro path. Il codice che state sviluppando attivamente sarà così disponibile dalla linea di comando. Questo funziona solo quando la directory in cui siete è un sandbox di cabal.
## Debian
### Usando Ubuntu PPA
Se non state usando Debian stable, le stesse istruzioni che abbiamo indicato per Ubuntu fuzionano, ma dovrete eseguire un comando in più. Immediatamente dopo che il comando
`sudo add-apt-repository -y ppa:hvr/ghc`
lanciate:
```bash
$ sudo sed -i s/jessie/trusty/g /etc/apt/sources.list.d/hvr-ghc-jessie.list
```
Per altre versioni di Debian dovete solo rimpiazzare tutte le occorrenze di `jessie` con il nome della versione che state utilizzando nel comando di cui sopra.
Se per qualche ragione il file `/etc/apt/sources.list.d/hvr-ghc-jessie.list` non dovesse esistere, allora `/etc/apt/sources.list` dovrebbe contenere una linea come questa:
deb http://ppa.launchpad.net/hvr/ghc/ubuntu jessie main
Rimpiazzate quindi in quella linea `jessie` con `trusty`.
### Compilazione manuale
Potete seguire
[questa](http://www.davesquared.net/2014/05/platformless-haskell.html) guida scritta per Mac OS X:
Note:
- Quando configurate ghc settate il prefisso appropriato
- Invece di prendere il binario di `cabal-install`, scaricate il codice sorgente e lanciate lo script
`bootstrap.sh`.
## Fedora 21
Per installare Haskell 7.8.4 dal repository non ufficiale (Fedora 22+ lo includerà ufficialmente):
```bash
$ sudo yum-config-manager --add-repo \
> https://copr.fedoraproject.org/coprs/petersen/ghc-7.8.4/repo/fedora-21/petersen-ghc-7.8.4-fedora-21.repo
$ sudo yum install ghc cabal-install
```
Come affermato in
[petersen/ghc-7.8.4 copr page](https://copr.fedoraproject.org/coprs/petersen/ghc-7.8.4/)
questo ghc non può essere installato insieme con il ghc di Fedora/EPEL.
## Arch Linux
Per installare Haskell dal repository ufficiale su Arch Linux, lanciate
```bash
$ sudo pacman -S cabal-install ghc happy alex haskell-haddock-library
```
## Gentoo
Su Gentoo, potete installare i singoli componenti della Haskell Platform
attraverso Portage. Se usate `ACCEPT_KEYWORDS=arch` (invece che
`ACCEPT_KEYWORDS=~arch`), Portage installerà versioni più vecchie di Haskell. Tenendone di conto, se usate `ACCEPT_KEYWORDS=arch`, aggiungete le seguenti linee a `/etc/portage/package.accept_keywords`.
dev-haskell/cabal-install ~arch
dev-lang/ghc ~arch
Una volta fatto quello, lanciate:
```bash
$ emerge -jav dev-lang/ghc dev-haskell/cabal-install
```
Gentoo include una versione "stabile" (leggi: vecchia) di `cabal-install` nell'albero di Portage, quindi vorrete usare `cabal-install` per installare la versione più recente. I backslash sono intenzionali.
```bash
$ \cabal update # I backslash
$ \cabal install cabal-install # sono intentionali
```
Adesso avete installato cabal a livello globale con portage, e localmente nella vostra home directory con `cabal-install`. Il prossimo passo è assicurarsi che quando lanciate `cabal` in un terminale, la vostra shell lanci la versione più recente che è nella vostra home directory. Aggiugete le linee seguenti nel file di configurazione della vostra shell:
```bash
PATH=$PATH:$HOME/.cabal/bin
alias cabal="$HOME/.cabal/bin/cabal"
```
Se non sapete quale shell avete, è molto probabile che la vostra shell sia Bash. Se usate Bash, il file che dovete editare è `~/.bashrc`. se usate Z-shell, il file è `~/.zshrc`. Potete lanciare il seguete comando per sapere qual'è la vostra shell.
```bash
echo $SHELL | xargs basename
```
Io uso zsh, quindi il comando restituisce `zsh` quando lo lancio.
Una volta fatto tutto questo, dovrete installare i tool addizionali `alex` e `happy`.
```bash
$ cabal install alex happy
```
Congratulazioni! Adesso avete una installazione di Haskell funzionante!
## Mac OS X
### 10.9
Installate [GHC per Mac OS X](http://ghcformacosx.github.io/), che include GHC e Cabal. La guida vi darà istruzioni su come installare GHC e Cabal nel vostro path una volta che avete copiato la .app da qualche parte sul disco fisso.
### 10.6-10.8
Eseguite l'installazione dei binari come scritto qui sotto usando [questo tarball](https://www.haskell.org/platform/download/2014.2.0.0/ghc-7.8.3-x86_64-apple-darwin-r3.tar.bz2).
## Windows
- L' [installer minimo per windows di GHC](http://neilmitchell.blogspot.com/2014/12/beta-testing-windows-minimal-ghc.html)
è in grado di compilare `network` e altro. È tecnicamente in beta ma dovrebbe funzionare per gli scopi di chiunque legga questa guida.
Non dimenticatevi di lanciare l'installer come amministratore, dato che è richiesto l'accesso alla directory di sistema 'Programmi'.
## Altri utenti Linux
Scaricate l'ultima distribuzione binaria di cabal e ghc:
- [GHC](http://www.haskell.org/ghc/).
- [Cabal](https://www.haskell.org/cabal/download.html).
# Corsi primari
## Il corso cis1940 di Yorgey
> *Seguite questo per primo*, è la strada che raccomando per il primo approccio ad
> Haskell.
Disponibile [online](https://www.seas.upenn.edu/~cis1940/spring13/lectures.html).
Il corso di [Brent Yorgey](https://byorgey.wordpress.com) è il migliore che ho trovato finora. Questo corso ha valore non solo perché vi rende in grado di scrivere codice Haskell basilare ma anche perché vi aiuterà a comprendere i parser combinators.
L'unica ragione per cui non dovreste cominciare con cis1940 è se non siete programmatori o se non avete molta esperienza. In questo caso, suggerisco di iniziare con il
[libro di Thompson](https://www.haskellcraft.com/craft3e/Home.html) e poi passate a cis1940.
---
## Il corso FP
> Questo è il corso che raccomando dopo cis1940 di Yorgey
Disponibile su github [qui](https://github.com/bitemyapp/fp-course).
Questo vi darà esperienza nell'implementare direttamente le astrazioni introdotte in cis1940. Questi esercizi sono *fondamentali* per sviluppare confidenza con gli usi comuni di Functor/Applicative/Monad/etc. in Haskell. La raccomandazione principale di questa guida è seguire cis1940 e poi FP: questo è il percorso che seguo per insegnare Haskell a tutti.
---
## Corso Supplementare cs240h
> Fornisce più materiale sugli argomenti intermedi
Disponibile [online](http://www.scs.stanford.edu/14sp-cs240h/).
Questo è il corso online di [Bryan O'Sullivan](https://github.com/bos) tratto dal corso che insegna a Stanford. Se non sapete chi è, date un'occhiata alla metà delle librerie che qualsiasi progetto Haskell richiede e ci troverete il suo nome. Sa avete già seguito il corso di Yorgey sono particolarmente rilevanti i moduli sui phantom types, il flusso di controllo delle informazioni, le estensioni del linguaggio, le concorrenza, le librerie pipes e lenses.
---
## Materiale di riferimento per i tre corsi
[Learn You a Haskell for Great Good (LYAH)](http://learnyouahaskell.com) e
[Real World Haskell](http://book.realworldhaskell.org) (Grazie bos!) sono disponibili online.
Raccomando RWH come referenza (è un libro spesso). I capitoli sul parsing e sulle monadi
sono ottimi per arrivare a capire l'utilità delle monadi stesse. Alcuni hanno detto che è piaciuto molto. Probabilmente è un buon follow-up per imparare gli idiomi in modo pratico, una volta che avete imparato le cose essenziali di Haskell?
### Cosa fa quel syntactic sugar `<-` / `do` / sulle list comprehension?
Eccellente [articolo](http://www.haskellforall.com/2014/10/how-to-desugar-haskell-code.html).
### Per capire list e fold
- [Explain List Folds to Yourself](http://vimeo.com/64673035)
### Per imparare alcune Typeclass di uso comune
Utile per capire `Functor`, `Applicative`, `Monad`, `Monoid` e altre Typeclass di uso comune, ma anche informazioni specifiche di Hask e di Teoria delle Categorie:
- La [Typeclassopedia](http://www.haskell.org/haskellwiki/Typeclassopedia)
### Capire i messaggi di errore più comuni di Haskell
- [Capire i messaggi di errore più comuni](http://ics.p.lodz.pl/~stolarek/_media/pl:research:stolarek_understanding_basic_haskell_error_messages.pdf)
---
# Laziness, strictness, guarded recursion
- Il [libro](http://chimera.labs.oreilly.com/books/1230000000929/ch02.html) di Marlow
sul parallelismo e la concorrenza ha una delle migliori introduzioni alla laziness e alla normal form che abbia trovato. Avrete bisogno di materiale in più se non acquisite i concetti subito.
- [More points for lazy evaluation](http://augustss.blogspot.hu/2011/05/more-points-for-lazy-evaluation-in.html)
- [Oh my laziness!](http://alpmestan.com/posts/2013-10-02-oh-my-laziness.html)
- Domanda su Stack Overflow '[Does haskell have laziness?](https://stackoverflow.com/questions/13042353/does-haskell-have-tail-recursive-optimization)'
- La presentazione di [Johan Tibell](https://github.com/tibbe) su
[reasoning about laziness](http://www.slideshare.net/tibbe/reasoning-about-laziness).
## Breve dimostrazione
```haskell
let a = 1 : a -- guarded recursion, (:) è lazy su di esso si può usare pattern matching.
let (v : _) = a
> v
1
> head a -- head a == v
1
let a = 1 * a -- non guarded, (*) è strict
> a
*** Exception: <<loop>>
```
# IO
- [Evaluation order and State tokens](https://www.fpcomplete.com/user/snoyberg/general-haskell/advanced/evaluation-order-and-state-tokens)
- [Unraveling the mystery of the IO monad](http://blog.ezyang.com/2011/05/unraveling-the-mystery-of-the-io-monad/).
- [First class "statements"](http://blog.jle.im/entry/first-class-statements).
- [Haddocks for System.IO.Unsafe.unsafePerformIO](http://hackage.haskell.org/package/base-4.7.0.1/docs/System-IO-Unsafe.html#v:unsafePerformIO)
Leggete la documentazione e le note sulla implementazione di unsafeDupablePerformIO
Commento da un thread di Reddit, di `glaebhoerl`
> Nota interessante: GHC deve nascondere la rappresentazione dello state token
> dietro un tipo IO astratto perché lo state token deve sempre essere usato linearmente (non
> duplicato o droppato), ma il type system non può garantire che questo accada. Clean, un altro
> linguaggio lazy come Haskell, ha 'uniqueness types' (sono come i linear types
> e possibilmente diversi per aspetti di cui non sono a conoscenza), e espongono
> World-passing direttamente e forniscono una monade IO (non astratta) solo per
> convenienza.
# Monadi and monad transformers
> Non cominciate a imparali finché non capite typeclass, Monoid, Functor e
> Applicative!
Implementate per conto vostro le monadi della libreria standard (List, Maybe, Cont, Error, Reader,
Writer, State) per capirle meglio. Poi potreste provare a scrivere un interprete monadico per piccole espressioni facendo riferimento all'articolo
[Monad Transformers Step by Step](http://www.cs.virginia.edu/~wh5a/personal/Transformers.pdf) (menzionata in 'monad transformers' qui sotto).
Scrivere diversi interpreti cambiando solo la monade per cambiare la semantica può aiutarvi a capire in che cosa consiste.
Poi reimplementate `Control.Monad`. Funzioni come `mapM` o `sequence` sono buone opportunità per fare esercizio e scrivere codice monadico generico.
Il corso FP può essere usato come guida a questo scopo, che include anche lo scrivere la vostra typeclass Applicative.
Referenza:
- Commenti su Reddit di htmltyp and Crandom [qui](https://www.reddit.com/r/haskell/comments/29eke6/basic_program_ideas_for_learning_about_monads/cik5aj6).
- Commenti su Reddit di jozefg [qui](https://www.reddit.com/r/haskell/comments/29eke6/basic_program_ideas_for_learning_about_monads/cik5trg).
## Monad transformers
- [A gentle introduction to Monad Transformers](https://github.com/kqr/gists/blob/master/articles/gentle-introduction-monad-transformers.md).
- [Monad transformers step-by-step](http://www.cs.virginia.edu/~wh5a/personal/Transformers.pdf) (attenzione il codice riportato è datato).
# Testare, test, specifiche, testing generativo e di proprietà
- Questo [tutorial](https://github.com/kazu-yamamoto/unit-test-example/blob/master/markdown/en/tutorial.md) di Kazu Yamamoto è fantastico.
- [Simple-Conduit](https://github.com/jwiegley/simple-conduit): Un'ottima libreria per imparare in modo semplice come funziona lo streaming IO in generale; la conoscenza è trasferibile a librerie più complesse come Pipes e Conduit
# Parsing in Haskell
- [Tutorial](https://github.com/JakeWheat/intro_to_parsing) sui Parser combinator
per Haskell, usando Parsec
- [Writing your own micro-Parsec](http://olenhad.me/articles/monadic-parsers/)
## Parsare e generare JSON
Aeson è la soluzione di parsing [JSON](https://json.org) standard in
haskell. Disponibile su [hackage](https://hackage.haskell.org/package/aeson) e
[github](https://github.com/bos/aeson).
- [Parsing JSON using Aeson](http://blog.raynes.me/blog/2012/11/27/easy-json-parsing-in-haskell-with-aeson/)
- [Aeson and user created types](http://bitemyapp.com/posts/2014-04-11-aeson-and-user-created-types.html)
- [Parsing non-deterministic data with aeson and sum types](http://bitemyapp.com/posts/2014-04-17-parsing-nondeterministic-data-with-aeson-and-sum-types.html)
- [Tutorial di Aeson](https://www.fpcomplete.com/school/starting-with-haskell/libraries-and-frameworks/text-manipulation/json)
# Algoritmi per grafi e strutture dati
- Il [pacchetto fgl](https://hackage.haskell.org/package/fgl) gli [algoritmi](http://hackage.haskell.org/package/fgl-5.4.2.2/docs/Data-Graph-Inductive-Query-SP.html) puramente funzionali per trovare la strada più breve.
- [Inductive graphs and Functional Graph Algorithms](http://web.engr.oregonstate.edu/~erwig/papers/abstracts.html#JFP01).
- [FGL/Haskell - A Functional Graph Library](http://web.engr.oregonstate.edu/~erwig/fgl/haskell/old/fgl0103.pdf).
- [Data.Graph source from Containers package](http://hackage.haskell.org/package/containers-0.5.5.1/docs/Data-Graph.html).
- Il [pacchetto graphs](https://hackage.haskell.org/package/graphs).
- [Domande su SO riguardo a PHOAS](https://stackoverflow.com/questions/24369954/separate-positive-and-negative-occurrences-of-phoas-variables-in-presence-of-rec)
- [PHOAS for free](https://www.fpcomplete.com/user/edwardk/phoas).
- [Tying the Knot](http://www.haskell.org/haskellwiki/Tying_the_Knot).
- [Hackage: dag](https://hackage.haskell.org/package/dag).
# Ambienti di sviluppo
## Emacs
- [Il tutorial di Alejandro Serras](https://github.com/serras/emacs-haskell-tutorial/blob/master/tutorial.md)
- [I miei dotfiles](https://github.com/bitemyapp/dotfiles/)
- [Il config emacs di Chris Done](https://github.com/chrisdone/chrisdone-emacs)
## Vim
- [Pagina di Vim su haskellwiki](http://www.haskell.org/haskellwiki/Vim)
- [Haskell-vim-now](https://github.com/begriffs/haskell-vim-now)
- [GHC-Mod](https://github.com/kazu-yamamoto/ghc-mod)
- [GHC-Mod vim plugin](https://github.com/eagletmt/ghcmod-vim)
- [Hindent](https://github.com/chrisdone/hindent)
## Sublime Text
- [SublimeHaskell](https://github.com/SublimeHaskell/SublimeHaskell)
# Lavorare con Cabal
## Linee guida di Cabal
Prima dell'introduzione dei sandbox, gli utenti Haskell incappavano nel problema definito Cabal Hell (Inferno di Cabal). Se non utilizzate una sandbox, cabal installerà il pacchetto nel vostro user package-db. Questa *non* è in genere una buona idea, fatta l'eccezione per alcuni pacchetti di base come
Cabal, alex e happy. Nient'altro dovrebbe essere installato nel package-db dell'utente né tanto meno a livello globale, a meno che non sappiate cosa state facendo.
Alcune raccomandazioni per non cadere nel Cabal Hell sono disponibili
[qui](http://softwaresimply.blogspot.com/2014/07/haskell-best-practices-for-avoiding.html).
Per provare un pacchetto o cominciare un progetto, iniziate lanciando
`cabal sandbox init` in una nuova directory.
In poche parole:
- Quando installate nuovi pacchetti, create nuovi progetti o pre-esistenti, o cominciate esperimenti usate sempre i sandbox.
- Usate `cabal repl` invece per iniziare una istanza di ghci come project-scoped
Questo approccio basato sui sandbox dovrebbe scamparvi dai problemi relativi alle dipendenze dei paccheti, ma è incompatibile con il modo in cui la Haskell Platform fornisce i pacchetti binari. Se state imparando Haskell e non capite come funzionano ghc-pkg e Cabal, *evitate la haskell platform*, ed usate invece le istruzioni all'inizio della guida.
## Stackage
Tutti gli utenti (di solito utenti di Yesod) che hanno problemi di build potrebbero provare ad utilizzare Stackage.
- Un buon riassunto di Stackage è
[qui](https://www.fpcomplete.com/blog/2014/05/stackage-server).
Secondo l'opinione dell'autore, Stackage è in genere più utile di `cabal freeze`.
# Hoogle e Haddock
## Ricerca di codice mediante type signature
Il [motore di ricerca Hoogle](http://www.haskell.org/hoogle/) può cercare per tipo.
Per esempio, guardate i risultati della ricerca per `(a -> b) -> [a] -> [b]`
[qui](http://www.haskell.org/hoogle/?hoogle=%28a+-%3E+b%29+-%3E+%5ba%5d+-%3E+%5bb%5d).
Lo trovate anche su fpcomplete [qui](https://www.fpcomplete.com/hoogle).
Anche [Hayoo](http://holumbus.fh-wedel.de/hayoo/hayoo.html) (che cerca su tutto Hackage per default).
## Setup della tua istanza locale di Hoogle
Guardate [qui](https://gist.github.com/bitemyapp/3e6a015760775e0679bf).
## Haddock
1. [Aggiusta la tua documentazione hackage](http://fuuzetsu.co.uk/blog/posts/2014-01-06-Fix-your-Hackage-documentation.html)
2. [Documentazione Hackage v2](http://fuuzetsu.co.uk/blog/posts/2014-01-06-Hackage-documentation-v2.html)
Fate attenzione, questi post sono *lievemente obsoleti*: per esempio, adesso Hackage vanta nuovi modi di mostrare informazioni, documentazione e stato del build.
## Quello che davvero avete bisogno di sapere
Per far includere ad haddocks la documentazione per i pacchetti correlati, dovete settare `documentation: True` nel vostro `~/.cabal/config`. Se lasciato sul valore di default (`False`) o settato a `False`, prima di rigenerare la documentazione dovrete rimuovere tutti i vostri pacchetti e reinstallarli.
L'altra cosa da tenere a mente è che a causa del modo in cui il parametro `$pkg` viene interpretato *da* cabal, non da voi, i parametri `html-location` e `content-location` *devono essere fra apici* e inseriti in una shell o in uno shell script. Non funzioneranno in un Makefile, perché crederanno di essere variabili di Make!
```bash
#! /usr/bin/env sh
# potete scrivero su una linea sola non mettendo backslash
cabal haddock --hoogle --hyperlink-source \
--html-location='http://hackage.haskell.org/package/$pkg/docs' \
--contents-location='http://hackage.haskell.org/package/$pkg'
```
# TravisCI
Se siete fan di [TravisCI](https://travis-ci.org) come lo sono io, allora vi consiglio
*caldamente* di dare un'occhiata a
[multi-ghc-travis](https://github.com/hvr/multi-ghc-travis) come base per il `travis.yml` dei vostri progetti Haskell.
# Frontend/JavaScript
Abbiamo l'imbarazzo della scelta! Ci sono tre scelte principali che raccomanderei:
* [Haste](http://haste-lang.org/) un compilatore da Haskell a JavaScript
- Il [compilatore](https://github.com/valderman/haste-compiler) su github.
- Una [demo](http://www.airpair.com/haskell/posts/haskell-tutorial-introduction-to-web-apps)
eccellente di Haste con un progetto di esempio.
* [GHCJS](https://github.com/ghcjs/ghcjs)
- [Introduzione a GHCJS](http://weblog.luite.com/wordpress/?p=14)
- [Functional Reactive Web Interfaces with GHCJS and Sodium](http://weblog.luite.com/wordpress/?p=127)
- [Writing Atom plugins in Haskell using ghcjs ](http://edsko.net/2015/02/14/atom-haskell/)
* [PureScript](http://www.purescript.org/)
- Non è strettamente Haskell come Haste e GHCJS, ma è una scelta popolare fra i programmatori Haskell
- Scritto in ed ispirato ad Haskell
- Provate purescript nel vostro browser [here](http://try.purescript.org/)
- Ottima guida per [cominciare a usarlo](http://www.christopherbiscardi.com/2014/06/22/getting-started-with-purescript/)
## Quale linguaggio scegliere per il frontend?
GHCJS e Haste sono entrambi interamente compatibili con Haskell. GHCJS è compatibile con un numero maggiore di pacchetti Haskell rispetto a Haste, ma questo non è rilevante per molti progetti frontend. Al contrario, PureScript non è Haskell, per tanto non potrete condividere il codice fra frontend e backend.
GHCJS ha un runtime più grande, a 100kb (luite ci sta lavorando). Haste e PureScript sono competitivi.
PureScript ha la migliore integrazione con i tool di JS (usa gulp/grunt/bower), mentre GHCJS
e Haste si integrano meglio con i tool di Haskell (Cabal).
Tutti e tre sono un'ottima scelta e possono funzionare per la maggioranza dei progetti frontend.
# Per una comprensione più profonda della laziness, NF, WHNF
- [Notes on lambda calculus](https://vec.io/posts/notes-on-lambda-calculus).
## Articoli di ricerca sul lazy lambda calculi
- [A call by need lambda calculus](http://homepages.inf.ed.ac.uk/wadler/topics/call-by-need.html#need-journal).
- [Demonstrating Lambda Calculus Reduction](http://www.itu.dk/~sestoft/papers/sestoft-lamreduce.pdf)
- [The lazy lambda calculus](http://www.cs.ox.ac.uk/files/293/lazy.pdf).
- [Lazy evaluation of Haskell](http://www.vex.net/~trebla/haskell/lazy.xhtlm)
# Parallelismo/Concorrenza
- Il libro [Parallel and Concurrent Programming in Haskell](http://chimera.labs.oreilly.com/books/1230000000929) di Simon Marlow è probabilmente il migliore che abbia mai letto sull'argomento.
- Un [walk-through](http://kukuruku.co/hub/haskell/haskell-testing-a-multithread-application) completo su testing e incremental development di un applicazione multi-threaded in Haskell.
- [Functional Reactive Programming](http://www.haskell.org/haskellwiki/Functional_Reactive_Programming)
# Lenses e Prisms
Una volta che vi trovate a vostro agio con Haskell, è molto utile imparare Lens e
Prism, anche se solo come "utente". Non avete bisogno di capire le categorie sottostanti
perchè vi siano utili.
La difficoltà di usare la libreria Lens è generalmente sovrastimata. Chiunque sia a suo agio con Functor/Foldable/Traversable (o anche solo il primo) può usare lens e prism per rendersi la vita più facile.
Se vi è capitato di fare qualcosa come: `(fmap . fmap)` stavate usando mentalmente le 'lenti'.
Raccomando questi due tutorial/introduzioni:
- [A little lens starter tutorial](https://www.fpcomplete.com/school/to-infinity-and-beyond/pick-of-the-week/a-little-lens-starter-tutorial)
- [Lens: Lenses, Folds and Traversals](https://github.com/ekmett/lens#lens-lenses-folds-and-traversals)
Leggete questo per maggiori informazioni: [pacchetto Lens su hackage](http://hackage.haskell.org/package/lens).
# Schemi di ricorsione
Alcune delle pazze parole di cui avete sentito parlare che finiscono con \*-morfismo riguardano la ricorsione. NB - prima di iniziare a studiare il materiale che segue dovreste sapere come implementare foldr per le liste e almeno un'altra struttura di dati, tipo un albero. (i fold sono catamorfismi) Sapere come implementare un unfold (anamorfismo) per le stesse strutture dati è complementare.
Questo materiale si compenetra con traversable e foldable.
- [An introduction to recursion schemes](http://patrickthomson.ghost.io/an-introduction-to-recursion-schemes/)
- [Don't fear the cat](http://fho.f12n.de/posts/2014-05-07-dont-fear-the-cat.html) -
Buona dimostrazione su come l'ilomorfismo sia la composizione di cata e ana.
- [Recursion Schemes](http://comonad.com/reader/2009/recursion-schemes/) - Questa guida è ottima.
- [Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire](http://eprints.eemcs.utwente.nl/7281/01/db-utwente-40501F46.pdf)
- [Catamorphisms](https://www.fpcomplete.com/user/edwardk/recursion-schemes/catamorphisms)
# GHC Core e ottimizzazione della performance
- [Write Haskell as Fast as C](write_haskell_as_fast_as_c.md)
- [GHC Wiki: CoreSyn Type](https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/CoreSynType).
- [Hackage: GHC Core](https://hackage.haskell.org/package/ghc-core).
- [SO Question: Reading GHC Core](https://stackoverflow.com/questions/6121146/reading-ghc-core).
- [Haskell as fast as C](http://donsbot.wordpress.com/2008/06/04/haskell-as-fast-as-c-working-at-a-high-altitude-for-low-level-performance/).
- [Real World Haskell, Chapter 25: Profiling and Optimizations](http://book.realworldhaskell.org/read/profiling-and-optimization.html).
# Tipi e Teoria delle Categorie
> *Non* è necessaria per scrivere Haskell, solo per quelli interessati!
Se volete imparare di più su tipi e teoria delle categorie:
- [La guida di Catster](http://byorgey.wordpress.com/2014/01/14/catsters-guide/) e [La seconda guida Catster](http://byorgey.wordpress.com/catsters-guide-2/)
- Il [wikibook haskell](http://en.wikibooks.org/wiki/Haskell/Category_theory) ha dei bei diagrammi
- [Teoria delle categorie](http://www.haskell.org/haskellwiki/Category_theory) su haskellwiki, ha anche buoni link ad altre risorse
- [Categories from scratch](http://science.raphael.poss.name/categories-from-scratch.html), include alcuni esempi pratici.
- La lista [Great Works in PL](http://www.cis.upenn.edu/~bcpierce/courses/670Fall04/GreatWorksInPL.shtml) di Pierce.
## Libri
- [Quora Question: What is the best textbook for category theory?](http://www.quora.com/Category-Theory/What-is-the-best-textbook-for-Category-theory?share=1) le raccomandazioni di Kmett
- [Awodey](http://ukcatalogue.oup.com/product/9780199237180.do) e
[MacLane](http://www.amazon.com/Categories-Working-Mathematician-Graduate-Mathematics/dp/0387984038). I libri di testo standard sulla teoria delle categorie
- [Harper's Practical Foundations for Programming Languages](http://www.cs.cmu.edu/~rwh/plbook/book.pdf) è la miglior introduzione alla teoria delle categorie focalizzata sui linguaggi di programmazione.
- [Type theory and Functional Programming](http://www.cs.kent.ac.uk/people/staff/sjt/TTFP/).
# Altri argomenti divertenti
## Parametricità, ad-hoc vs. polimorfismo parametrico e teoremi liberi
- [Parametricity](tony_parametricity.pdf).
- [Sorgenti TeX](https://github.com/tonymorris/parametricity/) per la presentazione di cui sopra.
- [Making ad-hoc polymorphism less ad-hoc](http://swizec.com/blog/week-20-making-ad-hoc-polymorphism-less-ad-hoc/swizec/6564).
- [Theorems for Free!](http://ttic.uchicago.edu/~dreyer/course/papers/wadler.pdf).
## Inizial e Final, DSL, Finally Tagless
- [Final Encodings, Part 1: A Quick Demonstration](http://creativelad.wordpress.com/2013/11/28/final-encodings-part-1-a-quick-demonstration/).
- [Transforming Polymorphic Values](http://martijn.van.steenbergen.nl/journal/2009/10/18/transforming-polymorphic-values/).
- [GADTs in Haskell 98](http://martijn.van.steenbergen.nl/journal/2009/11/12/gadts-in-haskell-98/).
- [Typed Tagless-Final Linear Lambda Calculus](https://www.fpcomplete.com/user/mutjida/typed-tagless-final-linear-lambda-calculus).
- [Typed tagless-final interpretations: Lecture notes](http://okmij.org/ftp/tagless-final/course/course.html).
- [Typed Tagless Final Interpreters](http://okmij.org/ftp/tagless-final/course/lecture.pdf).
- [The dog that didn't bark](http://existentialtype.wordpress.com/2011/03/21/the-dog-that-didnt-bark/) meno rilevante nello specifico ma comunque interessante.
## Comonadi
- [Comonads in Haskell](https://speakerdeck.com/dmoverton/comonads-in-haskell).
- [SO question: Can a Monad be a Comonad](https://stackoverflow.com/questions/16551734/can-a-monad-be-a-comonad).
## Yoneda / CoYoneda
- [SO question: Step-by-step explanation of coyoneda](https://stackoverflow.com/questions/24000465/step-by-step-deep-explain-the-power-of-coyoneda-preferably-in-scala-throu).
- Free monads for Less, una sequenza di tre articoli di Edward Kmett
* [Part 1: Codensity](http://comonad.com/reader/2011/free-monads-for-less/).
* [Part 2: Yoneda](http://comonad.com/reader/2011/free-monads-for-less-2/).
* [Part 3: Yielding IO](http://comonad.com/reader/2011/free-monads-for-less-3/).
## Propositions vs. Judgments (computazione)
- [StackExchange question: What is the difference between propositions and judgements](http://cstheory.stackexchange.com/questions/9826/what-is-the-difference-between-propositions-and-judgments).
- [Lecture notes from a short, three lecture course](http://www.ae-info.org/attach/User/Martin-L%C3%B6f_Per/OtherInformation/article.pdf)
# Tipi dipendenti
- [Grokking sum types, value constructors, and type constructors](http://bitemyapp.com/posts/2014-04-05-grokking-sums-and-constructors.html) strizzate gli occhi.
- [Lightweight Dependent-type Programming](http://okmij.org/ftp/Computation/lightweight-dependent-typing.html).
- [Idris programming language](http://www.idris-lang.org/).
# Linkare binari staticamente
- [Static linking](https://wiki.haskell.org/Web/Literature/Static_linking)
- [Static linking with GHC on Arch Linux](http://www.edofic.com/posts/2014-05-03-ghc-arch-static.html)
- [Statically linking Linux binaries for ARM & MIPS](https://stackoverflow.com/questions/14270177/ghc-statically-linking-linux-binaries-for-arm-mips-processors)
- [Statically link GMP using GHC and LLVM](https://stackoverflow.com/questions/10539857/statically-link-gmp-to-an-haskell-application-using-ghc-llvm)
## Dialoghi
> Disponibile in questo repository [qui](dialogues.md).
Questi sono in realtà importanti e utili. Leggeteli per approfondimenti su una varietà di argomenti.
================================================
FILE: guide-ja.md
================================================
# Haskellを学ぶ
これは、私が教えた経験に基づくHaskellの学習パスであり、[Haskell Book](https://haskellbook.com)の著者の一人が推奨するものです。
#### _すぐに理解できないことを気にする必要はありません_. 前に進みましょう!
## コミュニティ
私たちの IRC チャンネルは `#haskell-beginners` で、[Libera Chat](https://libera.chat/)にあります。
IRCウェブクライアントは[ここ](https://web.libera.chat/)にあります。
Haskellのメーリングリストは[ここ](https://wiki.haskell.org/Mailing_lists)です。
### コミュニティ・ガイドライン
IRCチャンネルで求められる行為については、[コミュニティ・ガイドライン](coc.md)を参照してください。荒らしかどうか判然としない場合は警告処分となりますが、このチャンネルは Haskell を学習したり教えたりする人たちだけのものであることに注意してください。
# Haskel
gitextract_f3yckcep/ ├── .gitignore ├── Contributing.md ├── LICENSE ├── Makefile ├── README.md ├── coc.md ├── code_to_learn_from.md ├── dialogues.md ├── guide-de.md ├── guide-el.md ├── guide-es.md ├── guide-fr.md ├── guide-hr.md ├── guide-id.md ├── guide-it.md ├── guide-ja.md ├── guide-ko.md ├── guide-pt.md ├── guide-ro.md ├── guide-ru.md ├── guide-sr.md ├── guide-tl.md ├── guide-tr.md ├── guide-ua.md ├── guide-zh_CN.md ├── guide-zh_tw.md ├── install.md ├── libraries.md ├── rts.md ├── specific_topics-ua.md ├── specific_topics.md ├── tools.md └── write_haskell_as_fast_as_c.md
Condensed preview — 33 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (436K chars).
[
{
"path": ".gitignore",
"chars": 37,
"preview": ".cabal-sandbox/\ncabal.sandbox.config\n"
},
{
"path": "Contributing.md",
"chars": 884,
"preview": "# CONTRIBUTING.md\n\n> Building the pdf requires pandoc.\n\n- Don't hyperlink anything that appears in the table-of-content."
},
{
"path": "LICENSE",
"chars": 6554,
"preview": "CC0 1.0 Universal\n\nStatement of Purpose\n\nThe laws of most jurisdictions throughout the world automatically confer\nexclus"
},
{
"path": "Makefile",
"chars": 773,
"preview": "PANDOC = pandoc\nINPUT = README.md\nINPUT_LANG = guide-$(GUIDE_LANG).md\nOUTPUT = tutorial.pdf\nOUTPUT_LANG = tutorial-$(GUI"
},
{
"path": "README.md",
"chars": 4958,
"preview": "# How to learn Haskell\n\nThis is a recommended path for learning Haskell based on experience helping others. A list of re"
},
{
"path": "coc.md",
"chars": 1640,
"preview": "# Code of conduct\n\n[See Chris Done's post on teaching](http://chrisdone.com/posts/teaching)\n\nBe kind and courteous. Bein"
},
{
"path": "code_to_learn_from.md",
"chars": 1685,
"preview": "# Note!\n\nCode listed isn't necessarily complete or a usable product. The point is that the resource linked is mostly cod"
},
{
"path": "dialogues.md",
"chars": 63294,
"preview": "# Dialogues from the IRC channel or other places\n\n## Transducers\n\n```\n19:31 < edwardk> bitemyapp: a transducer is recogn"
},
{
"path": "guide-de.md",
"chars": 34522,
"preview": "# Die Einführung\n\nDas ist mein empfohlener Weg Haskell zu lernen.\n\n*Beachte: Diese Einführung ist zwar in Deutsch, aber "
},
{
"path": "guide-el.md",
"chars": 0,
"preview": ""
},
{
"path": "guide-es.md",
"chars": 5563,
"preview": "# La Guía\n\nEste es el sendero que recomiendo para aprender Haskell.\n\n\n#### Para tener en consideración: *no te preocupes"
},
{
"path": "guide-fr.md",
"chars": 34013,
"preview": "# Le Guide\n\nCeci est ma façon recommandée d'apprendre Haskell.\n\n\n#### Quelque chose à garder en tête: *ne bloquez pas su"
},
{
"path": "guide-hr.md",
"chars": 4544,
"preview": "# Kako naučiti Haskell\n\nOvo je preporučeni put za učenje Haskella zasnovan na iskustvu u pomaganju drugim ljudima. Ovo j"
},
{
"path": "guide-id.md",
"chars": 5339,
"preview": "# Bagaimana cara belajar Haskell\n\nIni adalah langkah yang direkomendasikan untuk belajar Haskell berdasarkan pengalaman "
},
{
"path": "guide-it.md",
"chars": 33789,
"preview": "# La Guida\nQuesta è la strada che raccomando per imparare Haskell.\n\n## Per chi non parla italiano\n\n- [In English](README"
},
{
"path": "guide-ja.md",
"chars": 2624,
"preview": "# Haskellを学ぶ\n\nこれは、私が教えた経験に基づくHaskellの学習パスであり、[Haskell Book](https://haskellbook.com)の著者の一人が推奨するものです。\n\n#### _すぐに理解できないことを"
},
{
"path": "guide-ko.md",
"chars": 3420,
"preview": "# 하스켈 학습 가이드\n\n이 글은 여러분이 하스켈을 배우는데 도움이 될 수 있도록 경험을 바탕으로 만들어진 가이드로 [하스켈 북 (Haskell Book)](https://haskellbook.com)의 저자 중 한"
},
{
"path": "guide-pt.md",
"chars": 28477,
"preview": "# O Guia\n\nEste é o caminho que recomendo para se aprender Haskell.\n\n#### Uma coisa para se lembrar sempre: *não se preoc"
},
{
"path": "guide-ro.md",
"chars": 4543,
"preview": "# Ghid pentru a învăța Haskell\n\nAcest tutorial reprezintă calea recomandată pentru a învăța Haskell, pe baza experiențel"
},
{
"path": "guide-ru.md",
"chars": 33789,
"preview": "# Как познать Haskell\n\nЭтот документ — рекомендованный путь к изучению языка Haskell, основанный на опыте помощи другим."
},
{
"path": "guide-sr.md",
"chars": 4521,
"preview": "# Kako učiti Haskell\n\nOvo je preporučeni put za učenje Haskell-a zasnovan na iskustvu u pomaganju drugim ljudima. Ovo je"
},
{
"path": "guide-tl.md",
"chars": 5314,
"preview": "#Paano matuto ng Haskell\n\nIto ay ang maipapayong daan upang matutunan ang Haskell base sa karanasan na makatutulong sa i"
},
{
"path": "guide-tr.md",
"chars": 15349,
"preview": "# Nasıl Haskell Öğrenirim - Kılavuz\n\n Başkalarına yardım ederek deneyimlenmiş, Haskell öğrenmek için önerilen yöntemdir."
},
{
"path": "guide-ua.md",
"chars": 29031,
"preview": "# Як вивчати Haskell\n\nЦей документ є рекомендованим шляхом вивчання Haskell, який ґрунтується на досвіді допомоги іншим."
},
{
"path": "guide-zh_CN.md",
"chars": 2597,
"preview": "# 前言\n\n这是根据帮助别人的经验总结而来的一条 Haskell 学习路线,其中列出了 [Haskell 书](https://haskellbook.com/)的作者之一所推荐的一系列学习资料。\n\n#### _如果遇到不懂的地方也不要紧张"
},
{
"path": "guide-zh_tw.md",
"chars": 22650,
"preview": "# 前言\n\n這是我推薦的學習Haskell之路。\n\n#### 請切記:*別在不懂的地方打轉,先繼續讀下去!*\n\n## 社群\n\nIRC頻道是Freenode上的`#haskell-beginners`。\n\nIRC web版用戶端可[在這裡取得"
},
{
"path": "install.md",
"chars": 6653,
"preview": "# These instructions are deprecated\n\nWe now recommend you use [Stack](https://haskellstack.org) instead, but the instruc"
},
{
"path": "libraries.md",
"chars": 774,
"preview": "# Haskell tools for getting things done\n\nA curated list of Haskell libraries, packages, and tools\n\n\n## Data analysis\n\n##"
},
{
"path": "rts.md",
"chars": 1784,
"preview": "# Architecture\n\n- [Architecture of open source applications](http://www.aosabook.org/en/ghc.html)\n\n# Trac\n\nGood for digg"
},
{
"path": "specific_topics-ua.md",
"chars": 22540,
"preview": "# Конкретны теми для користувачів Haskell\n\n### Що роблять синтаксичні конструкції `<-` / `do` / спискове включення?\n\n[Чу"
},
{
"path": "specific_topics.md",
"chars": 22560,
"preview": "# Specific topics for Haskell users\n\n### What does that `<-` / `do` / list comprehension syntactic sugar do?\n\nExcellent "
},
{
"path": "tools.md",
"chars": 1405,
"preview": "# Tools\n\n\n## Don't install or try to use ghc-mod if you're a beginner\n\nIt's a bit fragile, more than a bit slow, and it'"
},
{
"path": "write_haskell_as_fast_as_c.md",
"chars": 18504,
"preview": "# Write Haskell as fast as C: exploiting strictness, laziness and recursion\n\n- 2008-05-16\n\n- by Don Stewart (dons)\n\n- Or"
}
]
About this extraction
This page contains the full source code of the bitemyapp/learnhaskell GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 33 files (414.2 KB), approximately 124.7k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.