[ cyb / tech / λ / layer ] [ zzz / drg / lit / diy / art ] [ w / rpg / r ] [ q ] [ / ] [ popular / ???? / rules / radio / $$ / news ] [ volafile / uboa / sushi / LainTV / lewd ]

λ - programming

/lam/bda /lam/bda duck
Name
Email
Subject
Comment
File
Password (For file deletion.)

BUY LAINCHAN STICKERS HERE

STREAM » LainTV « STREAM

[Return][Go to bottom]

File: 1431301001154.png (49.19 KB, 1000x716, url.png) ImgOps iqdb

 No.5965[Last 50 Posts]

Let's have a proper Haskell thread!
Post learning resources (beginner & advanced), neat tricks, stuff you wish you'd have known about sooner or simply talk about Haskell projects you are working on.

Currently reading the Haskell WikiBook at http://en.wikibooks.org/wiki/Haskell
I personally prefer it over lyah since lyah lacks exercises (I still skim through it since it is fun to read).
I also plan to work through "Thinking Functionally with Haskell" by Richard Bird, are there any opinions on this?
>>

 No.5966

I'm a novice programmer who knows only Python and I feel attracted to learn Haskell, but my older brother keeps telling me to not be ridiculous and learn C. What should I do?

>>

 No.5967

File: 1431302176258.jpg (17.24 KB, 288x288, taken_from_reddit.jpg) ImgOps Exif iqdb

>>5966
given that you know Python then C is a good follow up but if you really are interested in learning Haskell then just do it™.

>>

 No.5968

>>5966
I'd say give Haskell a try, the 3 languages you name go well together in my opinion, you know some Python which you can use to script, you can learn C to get a better unterstanding of "low level" stuff, and you can look into Haskell to learn some functional programming.
There is nothing "ridiculous" about learning Haskell, and C is not the only "true" programming language, don't believe simple, imprudent statements like that.
The main question you should ask yourself is "which one I take a look at first?".

>>

 No.5973

File: 1431350299603.pdf (1.69 MB, Thinking Functionally with….pdf)

This is by far the best introductary Haskell book on the market right now.
Enjoy.

>tfw unable to upload .epub

>>

 No.5974

File: 1431352329875.gif (489.47 KB, 320x240, url.gif) ImgOps iqdb

>>5973
Thank you for sharing, anon!
Have you already read the whole book?

>>

 No.5975

>>5974
Almost, I really should start doing all the excercises.
Also; here is the epub version:
https://lambda.moe/buks/Thinking%20Functionally%20with%20Haskell.epub

>>

 No.5990

Just started reading a cryptography book and began implementing its algorithms in Haskell.
Im very much impressed how easy this is and how few bugs occured.

Might make a github that contains what I learned so far.

>>

 No.5991

>>5990
what book? just curious.

>>

 No.5992

>>5991
Kryptologie from Beutelpacher
Obviously a german one.


>>

 No.6023

>>5993
They do look like fun.

When was the point you guys "got" monads? (Havent touched the topic yet)

>>

 No.6033

>>5993
Looks like nice exercises, thank you.
>>6023
After I got the type system and type classes. After that, the monad type class is nothing magical. Well, there are the monad laws, but they are straightforward

Just don't use the IO monad as an example. It exports no constructors and offers little opportunity to tinker with your code.

>>

 No.6035

>>6023
There isn't really much to "get", they're not that complex.

Applicative, on the other hand, that lets you do some really cool stuff.

>>

 No.6040

>>6035
All monads are applicative, though.

>>

 No.6050

>>6040
But not all Applicatives are Monads, and the ones that aren't can do neat things. For example, an error-handling applicative:


newtype Error e a = Error { runError :: Either [e] a }

instance Functor (Error e) where
fmap f (Error (Right a)) = Error $ Right a
fmap _ (Error (Left es)) = Error $ Left es

instance Applicative (Error e) where
pure a = Error $ Right a

(Error f) <*> (Error a) = Error $ case (f, a) of
(Right f', Right a') -> Right $ f' a'
(Left fes, Left aes) -> Left $ fes ++ aes
(Left es, _) -> Left es
(_, Left es) -> Left es


Now this can't be a Monad, because we don't have `(<*>) == ap`, but it *is* an interesting structure in its own right. It lets us run a collection of computations which may fail, gathering as many errors as we can, and then return them all in a list – or the correct result, if everything succeeded. If this was a Monad, we could only get the first error.

In fact, I'm using a variant of that Applicative in my Haskell compiler front end for resolving the definitions of names, as I want to be able to give as many ambiguous/undefined name errors to the user at once as possible.

You can also do neat things like have `(<*>)` execute its arguments in parallel, which again you can't do with `ap` because monadic bind is inherently sequential.

>>

 No.6058

>>6050
Ok, that Functor instance should actually be

instance Functor (Error e) where
fmap f (Error (Right a)) = Error . Right $ f a
fmap _ (Error (Left es)) = Error $ Left es

>>

 No.6121

Sooo, thinking about learning Haskell and got a quick question.

Are monads a "necessary evil", or are they a "powerful tool" (that just happens to be hard to grasp for some)?

>>

 No.6125

>>6121
They're a powerful tool. I think the problem is that the abstract concept of a monad is very poorly explained, and they have a reputation of being difficult to understand because of this.

Don't worry about writing code generic in the monad for now. Just use specific monads, and after a while you'll spot the pattern and can read the definition. Just like with any other abstraction.

>>

 No.6127

>>6121
That's probably not a good question. Abstraction in general is a powerful tool, and monads are yet another abstraction. Although, they're a bit more abstract than your typical C++ templates.

>>6125 mostly nailed it. When starting out, don't worry about the generalities, learn to use the specific instances and learn about extensions later, when you have a firm grasp of the language, the syntax and the type system.

The "problem" with "monads" is that people who don't understand the general form make tutorials explaining the specifics of Haskell Monads* as if they were the real thing.

I can only advise you not to read any of those tutorials, because most of them are pretty bad and will only hamper your understanding later, when you transition to the more abstract phase. (There are like 2 or 3 good tutorials, at best.)

*: Haskell Monads are technically lax monoidal functors, but more on that later.

>>

 No.6298

>>5973
>Started reading this
Wow the exercises in this book are quite challenging (in a good way).

>>

 No.6318

Any lainons use emacs with Haskell and don't mind sharing their dotfiles? I wanna see how you've got it set up for editing.

I tried setting up ghc-mod and company for auto completion just like the docs and guides say, but it doesn't work. The syntax checker works, oddly enough, which is in the same plug in. Yes I enabled the right back ends for company.

>>

 No.6361

this free online course is the best and easiest way to learn Haskell
https://www.edx.org/course/introduction-functional-programming-delftx-fp101x

>>

 No.6372

File: 1433133967350.png (68.04 KB, 1249x727, machines.png) ImgOps iqdb

Hey all, any tips on improving the Haskell code on the right?

Still learning, so I don't know any idiomatic Haskell.

>>

 No.6373

I know JavaScript and some Scheme and I love passing around functions from and to other functions (including using them to do mutation).

Now, how much deeper would the rabbit-hole go if I learn Haskell?

>>

 No.6374

>>6373
Once you start using Idris and reading HoTT, you know you've gone too far.

Haskell is great. Learn it!

>>

 No.6383

>>6372
>cond
>begin
Cond has an implicit begin.
Check out case.

>>

 No.6384

Tried to read "Learn you Haskell for great good" right?, then dropped it. Now this week listening to a guy that knows Haskell and it sounds good.

So, a question. Do I really need to know Haskell if I use C, Go and Rust?

>>

 No.6386

>>6384
No, but you don't need to learn Go or Rust to know C, and C is the most popular language in existence.

>>

 No.6387

>>6386
No, I [b]already[/b] use them all. I just want to know if Haskell is a good exp for me or not.

>>

 No.6388

>>6387
Ergh, mobile client uses BBcodes.

**test**

>>

 No.6389

>>6388
Yep, I am new to this imageboard.

>>

 No.6390

>>6383
Alright.

Any tips for the Haskell code?

>>

 No.6391

>>6388
[spoiler] then [/spoiler and close it

Welcome Newlain.

>>

 No.6393

>>6389
Go post here >>>/q/4678

>>

 No.6397

>>6387
Probably. If you like Rust, you'll probably like Haskell, too. You can do some cool low-level shenanigans with GHC. If you like Go more than C and Rust, Haskell is probably not for you.

>>

 No.6398

>>6372
One thing for now -- in runState, there's a repeating pattern:
_ -> (_ : ret, tl)

try to factor that out.

Also, make a separate case Sleep 0 so that you can get rid of the ugly if-then-else.

>>

 No.6413

>>6372
Rather than count up from n to 10 in mainLoop, it's often nicer to count down from some value to 0. That then makes it easy to change the number of iterations at the call-site, and also clearer how many iterations there will be.

>>

 No.6414

File: 1433370844816.jpg (109.89 KB, 717x757, weTrulyLiveInTheBestTimeEv….jpg) ImgOps Exif iqdb

Thank you #based anon.

>>

 No.6465

>>5993
Thanks anon.

>>

 No.6563

Any opinions on the upcoming book by Chris Allen?
http://haskellbook.com/index.html

Is he legit?

>>

 No.6783

>>5973
This is from the introduction:
> Even after 30 years I still get a great deal of pleasure from writing down a simple, obvious, but inefficient way to solve a problem, applying some well-known equational laws, and coming up with another solution that is ten times faster.
If it's so easy, why can't the complier apply the equational laws?

>>

 No.6784

>>6783
Because it's actually a computationally hard problem. It's not easy to write a deterministic algorithm for something like this. There have been some advances in machine learning, but any functioning and practically usable approach is probably still far away.

>>

 No.6814

How would image handling be done with Haskell? I want to learn haskell by re-implimenting a c++ program that I've written. Originally, I used a library to dump the pixel data into a vector and then re-encode it back into an image. What would be the closest analog I could get?

>>

 No.6815

>>6814
Personally, I haven't done anything like this in Haskell, but there was recently a thread about this in haskell-cafe:
https://mail.haskell.org/pipermail/haskell-cafe/2015-June/119935.html

>>

 No.6816

>>6815

Awesome. I'll look into this.

>>

 No.6835

File: 1434781579630.png (1.09 KB, 298x169, ghc.png) ImgOps iqdb

>>5965
Why is ghc so fuarrrking massive, lainons?

I want to learn Haskell, but I don't have the kind of space left in my root partition to install 900 MiB of compiler.

>>

 No.6837

>>6835
then use hugs

>>

 No.6838

File: 1434788206720.png (513.05 KB, 2150x1330, Screen Shot 2015-06-20 at ….png) ImgOps iqdb

>>6835

FPComplete's haskell center online ide is decent. Nothing to install. It's free and even has built in haskell tutorials (pic related). It's at least worth checking out.

https://www.fpcomplete.com/

>>

 No.6841

>>6835
I comes with tons of libraries while being a library as well.

And each library is there four times: a static version, a dynamic, a profiled and a GHCi version.

It is ugly, yes.

>>

 No.6842

>>6835
jesus fuarrrking christ that's almost as big as half of my arch install.

>>

 No.6858

>>6841
Are all of those libraries really necessary for learning the language? I figure by the time you're done with the book you can look up what libraries you need.

>>

 No.6889

>>6858
No, but it's convenient to just bundle them together and isn't usually a problem.

Incidentally, if you're on Arch, you might be able make a few gigabytes of space by running
# pacman -Scc

This deletes local copies of all of the packages you've got installed. If you haven't run it before, then you have a copy of every package you've ever installed saved there (including outdated versions).

>>

 No.7287

Lains that code Haskell in vim, what Plugins do you use?

>>

 No.7289

>>7287
I don't use any Haskell specific plugins, but there are a couple here http://vim-scripts.org/vim/scripts.html

>>

 No.7290

>>7287
I use "hdevtools" and "neco-ghc". Both compile and check your code in the background.
If you use systastic, I strongly reccomend using "hlint" with it.
There also are a few different syntax highlightin scripts that are better than the default.


>>

 No.7547

Learn You a Haskell for a Great Good was absolutely horrible. I also seem to have borrowed it forward somewhere and am not missing it one bit. That's my advice for this thread. Learning Haskell may be good, but not with that book. You aren't learning anything.

>>5973
Thanks lainon! I'll look into this!

>>

 No.7548

>>7547
>learn you a haskell is bad
is there an alternative that you would endorse?
if not, ill just go with:
>>5973
thank you anon

>>

 No.7550

>>7547
This is actually true, I would not call it horrible, but it's not a good book to actually LEARN haskell, it's more like a decent reference fore beginners. There are no exercises and most chapters are simply listings of functions.

>>

 No.7554

>>6121
>>6023
I never understood why monads confuse people (maybe it's just the name). For the purposes of programming, it's just a value in a box with a way to combine two values in a box and get a third value in a box. Haskell throws in another function that lets you temporarily unbox the value and use it to determine a different kind of value to put in a box.

They're not even really mind-blowing. It's just a specific case of a monoid. To be fair, I came to Haskell already knowing what groups, semigroups, monoids, and categories were (in their mathematical senses). But still, it's such a simple, obvious, and intuitive concept.

Now applicatives, those will change the way you program, like >>6035 said.

>>

 No.7585

>>7550
This. It pretty much just listst different things, explaining briefly how it all works. It doesn't have anything practical or in-depth musings about why things are done like they are done going on. It's like glorified Java API Doc merged with Stackoverflow. Something like Practical Common Lisp or Land of Lisp but for Haskell would be nice.

>>

 No.7844

I decided to finally add Haskell to my toolbox by learning it properly. I would very much like to have a book similar to Conrad Braski's Land of Lisp which introduced advanced concepts not so gradually but sprinkled among programming tasks as needed. Something with lots of hands-on tasks and is uptodate. Also, last time I tried Haskell I used Emacs with haskell-mode. Still the best choice?

By the way, thoughts on Elm? Seems awesome.
http://elm-lang.org/

>>

 No.7845

>>7844
>thoughts on elm
It's a cute reminder that javascript is turing complete. Honestly, though, it's a terrible way to make a website. It loads slowly, needs javascript enabled, and eats processor on the client machine. The best web pages are mostly static content, in my opinion. I guess Elm is a nice option if you're being forced into making a web app for some reason.

>>

 No.7885

>>7844
>Also, last time I tried Haskell I used Emacs with haskell-mode. Still the best choice?
Emacs is generally a pretty good choice.
I myself am quite happy with Leksah, even though its still in beta.

>>

 No.8308

File: 1438918737528.jpg (347.67 KB, 1024x768, K-hole.jpg) ImgOps Exif iqdb

So my computer is down and probably will be for a while and I'm jonesing for my haskell fix but all I have is my android. I was considering frege for something called eclipse but I don't even know where to begin and how not to install a bunch of useless soykaf.

I had one of those moments where things just started clicking and I was rolling through breakthrough after breakthrough and getting into real mind orgasming territory...

Anyways I figured I would ask if anyone knew their way around android IDEs? Also FP complete has consistent browser issues so yeah wish that was an option.

>>

 No.8315

>>8308
Sounds like a recipe for pain.
Touchscreens are for dumb execs to feel like they're getting soykaf done by pinch-zooming through your read-only data sets "in the cloud".

Get a RPi2 (or other tiny computer), hdmi->dvi cable (if applicable), and 16GB SDCard for $50
Install GHC and have at it.

It's no speed demon, but you've been meaning to profile your code on lower-end systems anyway, right? Present Day, Present Time! AHAHAHAHAHA!

>>

 No.8322

>>8315
Profile? No I'm just learning the language and designing some basic programs. And actually I have been meaning to buy a Rpi2...

>>

 No.8324

>>8308
>I had one of those moments where things just started clicking and I was rolling through breakthrough after breakthrough and getting into real mind orgasming territory...

I know it's not possible to convery in words what you meant but
care to elaborate a little? I love haskell and I'd like to get some inspiration to try it out again.
Thanks

>>

 No.8466

>>8324
didn't know anyone else responed besides that fuarrrking non answer idiot. infinite lists. what do I have to tell you before you find your motivation again fuarrrkboi?

>>

 No.9318

wish this thread wasnt dead. I highly recommend jekor's haskell vids to those finishing intro haskell books or even intermediate haskellers. my only complaint of the series is he sometimes makes a promise to explain something in detail in the next video but doesnt end up covering it. also probably not the best place to learn reactive programming but then again there isnt really a good place ive ever found.
https://www.youtube.com/playlist?list=PLxj9UAX4Em-Ij4TKwKvo-SLp-Zbv-hB4B
https://www.youtube.com/playlist?list=PLxj9UAX4Em-Lz5btngxMVZxf_B44GETVz

>>

 No.9321

>>7844
I haven't read Land of Lisp,
but Real World Haskell sounds like what you want.
In this book you basically just implement some things, while learning advanced concepts of the language here and there.
It's also freely available online!: http://book.realworldhaskell.org/read/

>>

 No.9419

Kinda cozy in here actually. Did a really light intro to vectors today
o-okay here I go:

-- | Main entry point to the application.
import Data.Vector as V


-- | create new vector

neuron = (V.replicate 1 5) V.++ (V.enumFromTo 1 3)
mapToNeuron = V.map (*2)
mappedNeuron = mapToNeuron(neuron)


-- | The main entry point.
main :: IO ()
main = do

putStrLn "vector: "
print $ mappedNeuron

>>

 No.9420

>>9419
it worked!

>>

 No.9422

>>9419
You've got some unnecessary syntax there lainon:


-- | Main entry point to the application.
import Data.Vector as V


-- | create new vector

neuron = V.replicate 1 5 V.++ V.enumFromTo 1 3
mapToNeuron = V.map (*2)
mappedNeuron = mapToNeuron neuron


-- | The main entry point.
main :: IO ()
main = do
putStrLn "vector: "
print mappedNeuron


Also, it's good practice to give all top-level definitions a type signature.

>>

 No.9425

File: 1442296627999.png (1.08 MB, 900x749, follow_your_dream_by_miruk….png) ImgOps iqdb

>>9422
Oh yeah look at that. It's all still very awkward- you know how babies flail around to get used to their bodies? and sometimes just soykaf everywhere? that's kinda what it feels like right now...

>>

 No.9477

>>9419
Cool, try messing around with your ideas and experimenting in the repl-- ghci is perfect for it. I played around with what you were doing to demonstrate a few things in ghci.

GHCi, version 7.10.2: http://www.haskell.org/ghc/  :? for help
Prelude> import qualified Data.Vector as V
Prelude V> -- qualified means we need to qualify imported definitions with a qualifier
Prelude V> -- by default this qualifier would be Data.Vector, however "as V" changes the qualifier to V
Prelude V> V.replicate 1 5
fromList [5]
Prelude V> -- ghci binds the last evaluated expr to the it variable
Prelude V> :type it
it :: Num a => V.Vector a
Prelude V> :t V.singleton
V.singleton :: a -> V.Vector a
Prelude V> let [x,y] = [V.singleton 5, V.enumFromTo 1 3]
Prelude V> x V.++ y
fromList [5,1,2,3]
Prelude V> -- Vector has an instance for Functor where fmap = map. fmap is common enough so it's aliased to the infix op (<$>)
Prelude V> (*2) <$> x V.++ y
fromList [10,2,4,6]
Prelude V> -- the haddock page for Data.Vector reveals Vector has a Monoid instance
Prelude V> -- https://hackage.haskell.org/package/vector/docs/Data-Vector.html
Prelude V> :info V.Vector
data V.Vector a
= Data.Vector.Vector {-# UNPACK #-}Int
{-# UNPACK #-}Int
{-# UNPACK #-}(primitive-0.5.4.0:Data.Primitive.Array.Array a)
-- Defined in ‘Data.Vector’
instance Eq a => Eq (V.Vector a) -- Defined in ‘Data.Vector’
instance Monad V.Vector -- Defined in ‘Data.Vector’
instance Functor V.Vector -- Defined in ‘Data.Vector’
instance Ord a => Ord (V.Vector a) -- Defined in ‘Data.Vector’
instance Read a => Read (V.Vector a) -- Defined in ‘Data.Vector’
instance Show a => Show (V.Vector a) -- Defined in ‘Data.Vector’
instance Applicative V.Vector -- Defined in ‘Data.Vector’
instance Foldable V.Vector -- Defined in ‘Data.Vector’
instance Traversable V.Vector -- Defined in ‘Data.Vector’
instance Monoid (V.Vector a) -- Defined in ‘Data.Vector’
Prelude V> -- well, what does it do?
Prelude V> -- a quick glance at the source for Vector's Monoid instance shows
Prelude V> -- (++) is defined as the monoid's operation, the empty vector as the monoid's identity element
Prelude V> -- https://hackage.haskell.org/package/vector-0.11.0.0/docs/src/Data-Vector.html#instance%20Monoid%20(Vector%20a)
Prelude V> -- mappend is an unfortunate name for the monoid operator, kept for compatibility reasons. it was later aliased to (<>)
Prelude V> import Data.Monoid
Prelude V Data.Monoid> x <> y
fromList [5,1,2,3]
Prelude V Data.Monoid> (*2) <$> x <> y
fromList [10,2,4,6]
Prelude V Data.Monoid> let f s t = (*2) <$> s <> t -- note how generic this function is
Prelude V Data.Monoid> :t f
f :: (Functor f, Num b, Monoid (f b)) => f b -> f b -> f b
Prelude V Data.Monoid> f x y -- it can be used with vectors
fromList [10,2,4,6]
Prelude V Data.Monoid> f [5] [1..3] -- as well as lists
[10,2,4,6]

>>

 No.9508

 
triangular :: Matrix -> Matrix
triangular [] = []
triangular m = row:(triangular rows')
where
(row:rows) = rotatePivot m
rows' = map f rows
f bs
| (head bs) == 0 = drop 1 bs
| otherwise = drop 1 $ zipWith (-) (map (*c) bs) row
where
c = (head row)/(head bs) -- suitable multiple


What exactly are f and bs? They definded nowhere, the code compiles however. It's part of an implementation of the Gaussian elimination algorithm.

>>

 No.9509

>>9508
Sure they are: `f` is defined inside that `where` block, and `bs` is the argument to `f`.

>>

 No.9510

>>9509
Oh, I completely misunderstood guards' definition then.

>>

 No.9514

>>9510
Here's it is rewritten to not use guards, and with perhaps clearer formatting:


triangular :: Matrix -> Matrix
triangular [] = []
triangular m = row : triangular rows'
where
(row:rows) = rotatePivot m

rows' = map f rows

f bs = if head bs == 0
then drop 1 bs
else drop 1 $ zipWith (-) (map (*c) bs) row
where
c = head row / head bs

>>

 No.9539

>>9514
Thanks, that does make it clearer.

>>

 No.9546

File: 1442550142075.webm (2.99 MB, 720x720, 1442461470141.webm) ImgOps iqdb

Did some more experimenting (ghci was yeah a little more nimble than the fp ide) the past couple of days but I ran into a problem using doubles in vectors- namely that I'm not sure how to get fromList to work with unboxed vectors? Basically, how to a vector of doubles?

I could multiply by 10^12 or w/e the float is and truncate or just use matrices and I'm definitely weighing the benefits of vectors right now...

I'm eager to get this neural net off the ground but haskell's lack of documentation makes it extremely difficult. I could've banged this out in c++ in a day but I went with haskell so I could learn it along the way and basically get two birds stoned at once.

>>

 No.9550

Do you have any tips for keeping motivation and to check if you're actually learning? I was going through Real World Haskell and I'm very early on, but then I got to this question:
>Write a function lastButOne, that returns the element before the last.

I eventually got an answer online after stressing over not being able to do it for about an hour, with this solution being what I was trying to do just, written out correctly.
lastButOne :: [a] -> a
lastButOne xs = head ((drop (length xs - 2)) xs)


I feel like I'm understanding what I'm studying, but then it gets down to it and I end up feeling as lost as ever. Do you have any advice on better understanding Haskell, and sticking with my study of it? I hope this is the best place to ask. Thanks.

>>

 No.9552

>>9550
You need to understand that simply not getting a concept at firt is part of the learning process. It's just like studying maths.

>>

 No.9555

>>9550
I'm pretty new to Haskell, but is there any significant difference between the above and

lastButOne :: [a] -> a
lastButOne xs = xs !! (length xs - 2)

Is one less efficient or anything? They both fail on [] and mine fails on a single element, but assuming there are checks.

>>

 No.9556

>>9555
>>9550
GHC does some pretty clever optimisation, so they might produce different code. But the problem with both is that they each do two traversals of the list: one for length, and one for drop or (!!).

This only does one:


lastButOne :: [a] -> a
lastButOne [a,_] = a
lastButOne (x:xs) = lastButOne xs


Not everything needs to be done with higher-order functions. Pattern matching and general recursion is also good.

>>

 No.9558

>>9556
Thanks. I've never been particularly good at recursion, understanding a written example is much easier than writing one.

>>

 No.9594

>>9550
Couldn't you just do this?


lastButOne = last . init


It's not fast, but seems like the most idiomatic haskell to me.

>>

 No.9613

Is Learn You a Haskell still good?

>>

 No.9615

>>9613
LYAH is only good on Tuesdays.

>>

 No.9622

File: 1442754496123-0.pdf (4.51 MB, Apress Beginning Haskell, ….pdf)

File: 1442754496123-1.pdf (828.86 KB, Programming In Haskell, Gr….pdf)

>>9613
Yeah its good but not perfect.
In fact there are several better books out there. But it is a good quick read to get an overview of the features of Haskell.

Pdf related, better book, more interesting projects in it (or actually: one big project used throughout the book, starting small and growing until you use almost every feature in Haskell to improve it)

>>

 No.9623

File: 1442754682295-0.pdf (5.32 MB, RealWorldHaskell.pdf)

File: 1442754682295-1.pdf (2.91 MB, Haskell School of Music.pdf)

File: 1442754682295-2.pdf (1.7 MB, Thinking Functionally with….pdf)

>>9622
crap, only wanted to upload one pdf. (Beginning Haskell)
Well while we are at it...

>>

 No.9624

>>9622
>one big project used throughout the book

Very cool, I always like books that do this. Thanks.

>>

 No.9648

Some gradudate student I talked to recommended to follow the guide at https://github.com/bitemyapp/learnhaskell where they recommend to start with http://www.seas.upenn.edu/~cis194/spring13/lectures.html

I am still at week 5 but it is very fun so far.

>>

 No.9732

File: 1442982241746.pdf (330.11 KB, mark.pdf)

>>6023
The point where I understood how to begin using monads is when I saw the translation between functions using `return' and `>>=' and the syntactic sugar (do-notation).

The point when I actually started to use monads is when I stopped caring about being explicit and accepted said syntactic sugar. This is also the point when I started writing actual programs in Haskell.

The point when I understood why monads are useful for encapsulating IO is when I took a course in computer semantics and read pdf related.

The point when I understood some of the data structures that follow naturally once you have a monad is when I took a course in category theory.

The last two are entirely optional unless you have a genuine interest in type theory and mathematics. This isn't even unique to monads either. You could probably do all of the above, in that order, for any type class or data structure. The difference with monads is that they have an unfamiliar and mathy sounding name.

>>

 No.9779

I'm working through the FP complete tutorials, and making much more progress than I did with "Learn You a Haskell" which I found frustrating and inane. The only other languages I've used are Python, Javascript and a bit of Racket, so it's a little different but not too hard to understand.

The music and Haskell book someone posted in this thread looks awesome

I hear a lot of bad things about the package manager - could someone explain what "cabal hell" is?

>>

 No.9781

>>9779
>cabal hell
from: https://wiki.haskell.org/Cabal/Survival

1 What is the difficulty caused by Cabal-install?

The main difficulty with Cabal is otherwise known as 'dependency hell', in which the cabal-install does not manage to install a desired package for a reason or another, leading to large amount of manual work. As an example of this difficulty, consider a case where the user wishes to install packages A and B. Both of these work with package C, but not with the same version of C.

But also very important:

Historically, Cabal-install has often been the part of Haskell ecosystem that causes most of the beginner troubles. Currently (2013/spring) this tool is in a very usable condition and causes but a few difficulties for most people. However, there are people for whom it does not seem to work and who are very vocal about their issues. It seems that many of these problems get solved through discussions in IRC or other forums, but the solutions are not officially documented anywhere. Further, due to historical reasons there is some advice, such as deleting all installed packages at the first sign of trouble, which is not relevant anymore.

>>

 No.9798

>>9781
I never understood why this isn't a problem with other languages' package managers. What makes Haskell special? Is it because every package is compiled and linked at install time, so A is forced to use C version x, which it was compiled for, instead of C version y, which is also compatible with A, but required for B? Why is this not a problem with e.g. Rust/Cargo?

>>

 No.9805

>>9798
Well most languages dont have a package manager.
And rust is probably too new to have enough of such problems that it becomes known for it.

>>

 No.9819

>>9798
The this is cabal *isn't* a package manager, it's a build system. It was never intended to manage packages.

>>

 No.9824

>>9819
Does Haskell have a real package manager? I'm looking at nixos and stackage just so I never have to deal with anything that's nickname is hell..

>>

 No.9896

>>9824
No (like >>9805 said most langs don't have a package manager). I think the general expectation is that you use the package manager that comes with your distribution instead of having a dozen different ones for every single language, but it raises an interesting question about how to handle packages in non-standard languages.

>>

 No.9902

>>9824
`stack` is pretty good. It's again more of a build tool than a package manager, but it uses Stackage and so can ensure everything builds properly, and will continue to build properly, whilst still sharing a lot of build artefacts.

I've been using it for all my projects for a few weeks now and it's definitely more streamlined than cabal sandboxes.

>>

 No.9920

OK I'm attempting to rewrite a rhyming dictionary model I made in Python in Haskell. I'll post it up here for you guys to ridicule when I'm done

>>

 No.10315

What's the verdict on this course? Starts in a week:

https://www.edx.org/course/introduction-functional-programming-delftx-fp101x-0

>>

 No.10335

>>10315
I took it last year and I thought it was pretty decent.

>>

 No.10369

>>10335
not that lainon but could you give us a quick summary?

>>

 No.10371

>>10369
The class focuses on functional programming concepts like Higher Order functions and monads. One thing the instructor tries to drill into you is to trust the type system of Haskell and use it to help solve the problem.

>>

 No.10375

>>10371
I've never used EDX, but are things "gated off" after the due date? It doesn't say self-paced or self-study anywhere, but I'd like to go through with it but I have real life classes that are a bit more important. If the exercises are taken away I'd rather not waste my time.

>>

 No.10481

File: 1444638146631.png (514.21 KB, 810x698, e52622f06026c200bd7d9f1bf2….png) ImgOps iqdb

>>9824
It depends on how we're defining package management. For Haskell-level dependencies only, you currently have cabal-install and stack as options, both using Cabal library as a back-end. I have only tried stack when projects at work use them. I had mostly positive experience but had to contribute some patches and file some issues. A big advantage of stack over cabal-install is that getting features in is *a lot* quicker. It also caters to things like using Stackage LTS snapshots out of the box which is important when you're releasing a product and want to have an easier time later.

Then again, you can get by fine with cabal-install and its sandboxes but it's more manual labour. Unless you want to spend hours a day re-compiling lens, you're going to be manually linking sandboxes with pre-built sources. You also need to know what's going on so you don't get into sticky situations. cabal-install is getting better and is going to keep getting better, I just fear that it got somewhat of a bad name recently.

You can of course argue whether these count as package managers: they can't uninstall packages in the classical sense for example. An old post by Gentoo Haskell package set maintainer at the time goes over this briefly, you can find it if you search for ‘cabal is not a package manager’ I believe.

Then there is system-level package managers. These can handle providing system libraries that your Haskell packages need. The problem with these usually is one of these things:

* packages are too old
* package versions can't be mixed
* packages conflict with any packages installed by user manually with cabal-install &c.

Personally I use nix (on NixOS) and had good luck with it. Packages are upgraded fairly frequently. It does only keep one set of packages at one time as the default set which you may see as a problem. You can however pin nixpkgs version to a set you want. In recent weeks, snapshots of the stackage LTS releases have been added which covers that use-case. I highly recommend nix on any system, not just NixOS. Feel free to drop any questions, I don't know when I'll see them though.

>>

 No.10709

>>10335
>>10371
thanks again for this. i'm enjoying it thus far. the lecturer is a funny guy.

>>

 No.10773

I am in C and Python now, but i want to get functional. Is haskell great way? I like syntax more than lisp.

>>

 No.10800

>>10773
you can learn (and work well enough with) functional programming in Python.

Haskell isn't the worst choice though recent changes will set the bar substantially higher for beginners.

>>

 No.10814

>>10773
Haskell is honestly by far the best language to learn functional programming.
It is pure, yet allows for side effects via Monads, so you can actually be productive in.
The compiler is top-notch and gets better and better every release.
Huge active community releasing new stuff and packages regularly.
Code is reasonably fast naturally and comes within 20% of runtime speed of C code with optimization turned on.
The type system works like a charm.
Often times when your code compiles it will be bug free.
If you want to be sure, run Quickcheck over it, a testing tool that is the gatling canon to Unit testings slingshot.

>>

 No.10821

>>10814
Monads are not necessary for I/O in a pure language.

eg, in the early days, you had main :: [Response] -> [Request], which were infinite lazily constructed lists: [Response] by the runtime, [Request] by your program. They also tried out a continuation-based approach for a while too, where every I/O action had a success continuation and a failure continuation.

The reason I bring this up is that I find throwing the term "monad" around beginners tends to have a negative effect: because they think "Oh, this concept is clearly so important and universal I must learn it!", so they google for "monad tutorial", and most of them are soykaf .

>>

 No.11423

Where were you when Haskell was kill, Lains?

https://mail.haskell.org/pipermail/ghc-devs/2015-October/010068.html

tldr: every datatype in Prelude is now requiring Lens which breaks compatibility
with a lot of older Haskell software, creating a similar conundrum to Python 2.
7/3.x

A page about the harmful lens package: https://ro-che.info/articles/2014-04-24-lens-unidiomatic

So, what functional language should we move onto next?

>>

 No.11424

>>10821
The thing about Monads is that they are pretty universal though,
not only in Haskell, but also in Category Theory and Mathematics in general. (well a lot of concepts in cat are of universal nature...)
One would have a use for Monads in Haskell even without IO (chaining Maybe computations, or List comprehension or example).
So all in all Monads are a really great generalized solution to the Problem of IO,
and a quite natural one too.

>>

 No.11425

>>11423
This is why you use languages that have a recognized standard.

>>

 No.11435

>>11423
I didn't see anything about requiring lens in the future. Do you say `lens` when you mean `Foldable` and `Traversable`?
Also, in my opinion, lens is an example of what makes haskell so great. Instead of having to implement features at the language level, haskells type system and compiler are powerfull enough to be able to express complicated concepts in pure haskell.

>>

 No.11440

>>11423
>tldr: every datatype in Prelude is now requiring Lens
wtf? What is that tl;dr of? Mark said he wasn't happy with FTP (Foldable/Traversable in Prelude proposal) and that he's stepping down as the release manager of Haskell Platform.

As to your second question, Idris is getting better and better, so that's one option. Another is OCaml, which has its quirks too, of course. Personally, I'm sticking with Hakell for now.

>>11425
Haskell does have a standard and even a committee.

>>

 No.11447

>>11423
You obviously didn't read it.

A page about the marvelous aspects of lenses, and how they allow you to be more clear: http://www.haskellforall.com/2015/10/explicit-is-better-than-implicit.html

>>

 No.11448

>>11440
Foldable/Traversable and Applicative/Monad were incredible, I don't see reason to not like it besided breaking your old code (which can be repaired fairly easily) or for teaching purposes (like Erik Meijer's rant about using Hugs).

>>

 No.11452

>>11448
Agree.
>inb4 muh "length (1, 2)"

>>

 No.11471

>>11448
My issue with Foldable is that I've never seen a case where it's clearer to write some code such that it was *truly* generic in which Foldable instance it took, in the same way I write code which is generic in the Monad, or the Applicative, or the Traversable.

Every time I have been able to use a Foldable function, I have also known the concrete type I am folding over. So it kinda feels like: why bother with the abstraction, then?

>>

 No.11478

>>11471
Don't worry. You probably just don't understand either Foldable or abstraction in general.

>>

 No.11504

>>11478
Except I clearly do, because I said I write code which is generic in other typeclasses. Did you even read my post?

>>

 No.11507

>>11471
>>11504
Well, look at other peoples code if you are interested in which way they may generally use it.
I actually cant think of an example as well,
but there is probably more than one.
Either way, foldable is at least pretty idiomatic haskell,
so I don't have any qualms about it.

>>

 No.11537

>>11504
Writing code doesn't imply understanding.

>>

 No.11618

Can someone educate me on what the best practice for the folder structure of a small Haskell project is?

Still a bit confused on this.

>>

 No.11621

>>11618
Copy the `stack init` structure and stuff should be ok.

>>

 No.11628

Come, write Haskell

https://coderpad.io/2Z9D94AE

>>

 No.11648

Can you guys recommend me some advanced haskell resources?
I'm currently at the level of understanding monad transformers (having read Real World Haskell).
What's the best way to go from here on out?

>>

 No.11656

>>11648
Have you checked out Functional Pearls?
As for advanced books, I can only recall two from the top of my head:
- Okasaki: Purely Functional Data Structures
- Bird: Pearls of Functional Algorithm Design

Hope it helps. Let me know if you need some more pointers or are looking to expand in a specific direction.

>>

 No.11670

>>11656
Thanks for the reccomendations.
I have no specific direction right now.
I know that there are a few more concepts, like comonads and arrows I have to learn about.
I also believe there's quite a few neat things the type system can offer if you enable some GHC extensions, which I don't know much about either.

>>

 No.11699

File: 1446978199091.jpg (127.34 KB, 1200x1850, awodey.jpg) ImgOps Exif iqdb

>>11670
I don't think there are any books specifically aimed on the more advanced Haskell-category-theoretical concepts like comonads, but there are some blogs that you might want to check out. Three I can think of right now:
> Dan Piponi's 'A Neighborhood of Infinity'
http://blog.sigfpe.com/
> Bartosz Milewski's Programming Cafe http://bartoszmilewski.com/
> The Comonad Reader
http://comonad.com/reader/

If you like Functional Pearls, you might also like the Monad Reader: https://themonadreader.wordpress.com/

If you're feeling _really_ adventurous, you might just as well jump straight into the rabbit hole, and peruse something like Awodey's 'Category Theory'. Alternatively or in parallel, check out the videos and lecture notes from the Oregon Programming Languages Summer School: https://www.cs.uoregon.edu/research/summerschool/summer12/curriculum.html
It's been going for eleven years now (2005–2015), adjust the URL as needed for more sweetnes.

>>

 No.11700

>>11656
Is there a full version of Purely Functional Data Structures, or is the thesis the final version?

>>

 No.11702

File: 1446981237204.djvu (3.47 MB, Purely-Functional-Data-St….djvu)


>>

 No.11704

>>11670
There's also the Typeclassopedia: https://wiki.haskell.org/Typeclassopedia

>>

 No.11721

>>11670
>>11704
This, it's the easiest introduction to all these classes.

I studied category theory before knowing Haskell exists, and the feeling is not exactly the same. While I think CT is amazing and pure love, don't start reading mathematics books, it will not help you very much with Haskell.

>>

 No.11724

File: 1447029754831.jpg (52.06 KB, 1024x1024, :^).jpg) ImgOps Exif iqdb


>>

 No.11764

>>11648
I just found this guide:
https://github.com/bitemyapp/learnhaskell/blob/master/specific_topics.md
It seems to cover a lot of the advanced topics, maybe it can be of use to someone else as well.

>>

 No.11851

Can someone help me setup my basic, global stack config?
I read
https://github.com/commercialhaskell/stack/blob/release/doc/yaml_configuration.md

It says to put


templates:
params:
author-name: Your Name
author-email: youremail@example.com
category: Your Projects Category
copyright: Copyright: (c) 2015 Your Name
github-username: yourusername


into the config.yaml. But when I put it in there like this, I get an InvalidYaml error. I can't find a proper config.yaml example.

>>

 No.11852

>>11851
>Copyright:
the problem. enclose in quotes if you need that.

>>

 No.11853

>>11852
thank you very much! that did the trick

>>

 No.11985

How do people keep up with the Haskell world?

I've been working in Haskell semi-regularly since ~2008, and have been pretty comfortable with the language's developments and felt that I've been at least somewhat in the loop. Though suddenly, it looks like there have been lots of changes that I only now hear of.

For example, I seem to have completely missed the Foldable-Traversable-Proposal and Monads finally becoming a superclass of Applicative and Functor. And when did people move to stack? I'm still not entirely sure what problem it solves (it's not cabal hell, from what I've gathered).

Have I been living under a rock without realizing it?

>>

 No.11988

>>11985
You've just been free from side effects this whole time.

>>

 No.11989

>>11985
There are only two resources that I peruse that keep me up to date: the haskell-cafe mailing list, and /r/haskell.

The former I read weekly only to catch up on some interesting discussions, should they take place, but they're usually reposted on Reddit anyway.

The latter, I visit twice a day to twice a week. There is usually at least one interesting thread on the front page, and I can easily catch up with the breaking news by looking at the top topics in the last week or so.

>>

 No.12028

File: 1447651915832.jpg (42.41 KB, 669x746, 1435194745803.jpg) ImgOps Exif iqdb


>>

 No.12068

File: 1447776309345.jpg (36.63 KB, 960x639, comfy_by_marustagram-d81jp….jpg) ImgOps Exif iqdb

>>11988
mfw no side effects

>>11985
I'd also recommend the mailing list as well as /r/haskell, also follow some of the popular "haskell guys" on twitter
#haskell IRC also often has interesting discussions on current topics

>>

 No.12135

trying to get my first tiny haskell program running, i read and write something from one file to another, it works fine if I use readfile on "file.txt", but how do I access a file if it is not in the same folder as the source file itself? "../folder/file.txt" does not work

>>

 No.12144

>>12135
Yes it does. Are you sure you got the path right?

$ mkdir a b
$ echo "hello" >> a/foo
$ cd b
$ ghci
GHCi, version 7.10.2: http://www.haskell.org/ghc/ :? for help
Prelude> readFile "../a/foo"
"hello\n"

>>

 No.12151

>>12135
Absolute paths work too.

>>

 No.12156

Just found these slides about type classes.
Especially the second part about instance resolution could also be of interest to advanced haskellers.
http://people.cs.kuleuven.be/~tom.schrijvers/Research/talks/lhug_s02e01.pdf

>>

 No.12158

>>12135
If you want to find the path of a data file to be included with your project, cabal auto-generates a module called
Paths_yourproject
that defines the install directories. Any data files (declared with
data-files
in your .cabal) would then end up in the data directory.

Example of the generated module:

$ cat dist/build/autogen/Paths_balls.hs
module Paths_balls (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where

import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude

catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch

version :: Version
version = Version [0,1,0,0] []
bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath

bindir = "/home/me/src/balls/.cabal-sandbox/bin"
libdir = "/home/me/src/balls/.cabal-sandbox/lib/x86_64-linux-ghc-7.10.2/balls-0.1.0.0-GyafO7tudcU0z1rnW9wBU3"
datadir = "/home/me/src/balls/.cabal-sandbox/share/x86_64-linux-ghc-7.10.2/balls-0.1.0.0"
libexecdir = "/home/me/src/balls/.cabal-sandbox/libexec"
sysconfdir = "/home/me/src/balls/.cabal-sandbox/etc"

getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "balls_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "balls_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "balls_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "balls_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "balls_sysconfdir") (\_ -> return sysconfdir)

getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)


So, you could run getDataDir or getDataFileName to find your file. To override the default paths, you could use the
--prefix
flag for
cabal configure
before building the project or set the
yourproject_datadir
environment variable when calling the program. Not sure how to use the former option with stack, though, if you're using that.

>>

 No.12337

>>12158
This is a nice thing to know, thank you lainon.

>>

 No.12346

Hi fellow haskellers, I come to you with a question as well: How do I pass functions of an imported module?

Let's say I got Module A which imports a library, and a Main.hs which imports Module A, how do I use specific functions from the library in my Main.hs?

I know I could import the library in my Main.hs as well, but this seems redundant to me.

>>

 No.12347

GHC replacement without FTP when?

>>

 No.12348

>>12347
Use Hugs or GHC 7.8. But why the hell would you want it? You just lose power.

AMP is less clear for me, as I'm not 100% sure that the monad you find useful in your code is always derived from the applicative you find useful. But still, it is nice.

>>

 No.12349

>>12346
You have to import them explicitely. Or if you want to use few things, use:

import Data.List (sort)

and say exactly what you are using in your code.

If that bothers you fundamentally, maybe you could modularize better your code.

>>

 No.12350

Why do Haskellites exaggerate the complexity of monads?

>>

 No.12351

>>12350
Once you understand what monads are, and why they exist, you lose the ability to explain it to anybody. – Douglas Crockford

>>

 No.12352

>>12350
To feel superior to others.

>>

 No.12353

>>12349
>maybe you could modularize better your code

guess you are then, thank you though

>>

 No.12354

>>12353
*right

>>

 No.12355

>>12350
They do not exaggerate, it is just vocabulary-heavy and you get used to it. And this is the kind of stuff that is very easily and clearly expressed with the right vocabulary, and just vague when you use non-technical words.

>>

 No.12356

>>12355
I like the saying "Enlightenment is being able to explain to the ignorant."

In other words, if you can't explain the concept in plain english to someone, you probably don't actually know what you're talking about.

In the case of monads, they seem to be the usual mental masturbation, so it's only exacerbated.

>>

 No.12357

>>12356
You can make methaphors and make the person feel she understood, but in most cases you just really learn by doing.

There are two cases where you want to explain things to laymen. One is when they are learning it so they can use it. In this case, they have to get a hold in it and really understand. The second case is when you are justifying your work, trying to make people interested, etc... In this case you just want to make people feel they understood the basic, but in most cases it's just a temporary sensation.

I don't really believe that you teach people, they learn with what you say. There are better or worse ways, but neither is done without work.

And monads in Haskell are very far from being mental masturbation. It is an abstraction, but one that allows you to do a really large quantity of stuff elegantly and efficiently.

People are just afraid of new words.

>>

 No.12359

>>12350
Where did you gain that impression? Literally every tutorial and attempt at explaining monads I've read starts with or contains something like "monads are really simple".

>>12356
It doesn't make sense to explain it in "plain English". Sure, you can use analogies and metaphors (burritos, kek), but the explanation will only be limited to a narrow abstraction of a particular instance of the concept. The "problem" with monads is that they're very abstract, and natural languages like English are not fit for this level of abstraction.

>>

 No.12360

>>12357
>>12359
This all reminds me of a different conversation I was having with a Haskell programmer.

I had grown unfamiliar with the term function composition. Of course I knew what it was, since I use it so often, but the Haskell programmer acted like he was superior because he remembered the term.

Since this is a Haskell thread, how about you two just try to explain monads? Anything abstract can be boiled down slowly to less abstract concepts.

>>

 No.12361

>>12360
>Since this is a Haskell thread, how about you two just try to explain monads? Anything abstract can be boiled down slowly to less abstract concepts.

A monad is a parameterised type along with definitions of fmap, pure, (<*>), and (>>=) satisfying the functor, applicative, and monad laws. That's it.

>>

 No.12362

>>12361
That's a good start.
Now define the following:
parameterised type
definitions
fmap
pure
(<*>)
(>>=)
satisfying
functor, applicative, and monad laws

>>

 No.12363

>>12360
>the Haskell programmer acted like he was superior because he remembered the term.
He was probably just a pretentious cunt.

>how about you two just try to explain monads?

Just look at one one of the myriad tutorials that have been written over the years: https://wiki.haskell.org/Monad_tutorials_timeline
There's no point in repeating the same points and making the same mistakes that lead to confusion along the way. If you have any specific points you want to discuss, bring them up.

>>

 No.12385

>>12363
>If you have any specific points you want to discuss, bring them up.
I wanted to read the first tutorial from the 90s, but it wasn't available.

My understanding is now that monads support returning values and also feeding them into other computations with >>=.
I've read that you can add on to this, although not shown how you can, to get state, IO, and exceptions.
From this, I've been told that monads let you create an environment that only has what you need.

That sounds interesting and reminds me of the package system in Common Lisp. I can avoid including whatever features I want in a package. I can also modify the read table global variable to disable access to features. It would be possible to replace Common Lisp's exception system with my own by aggressively creating such a package and access to certain datatypes can be restricted easily by simply disallowing use of functions and reader macros that create them.

>>

 No.12386

>>12385
>I wanted to read the first tutorial from the 90s, but it wasn't available.
Weird. I seem to have had it in cache, but after flushing, the server doesn't respond. It's in the Archive anyway: https://web.archive.org/web/20150423203821/http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf

>>

 No.12390

>>12385

Here's how you (could) define a state monad:

newtype State s a = State { runState :: s -> (a, s) }


"State s a" is a box containing a function of type "s -> (a, s)", which can be extracted with "runState". So here, the "state" is a represented as a single value: you supply an initial state, and you get back a result and a final state.

instance Functor (State s) where
fmap :: (a -> b) -> State s a -> State s b
fmap f sa = State $ \st -> let (a, st') = runState sa st in (f a, st')


The Functor instance lets you apply a function to the result value, possibly changing its type. It doesn't let you do anything to the state value though. This is because Functor has kind "* -> *", whereas "State" has kind "* -> * -> *", so the first type parameter needs to be fixed.

instance Applicative (State s) where
pure :: a -> State s a
pure a = State $ \st -> (a, st)

(<*>) :: State s (a -> b) -> State s a -> State s b
sf <*> sa = State $ \st -> let (f, st1) = runState sf st
(a, st2) = runState sa st1
in (f a, st2)


Applicative lets you put values into State, and to apply a stateful function to a stateful value: and thread through the state from left to right.

instance Monad (State s) where
(>>=) :: State s a -> (a -> State s b) -> State s b
sa >>= f = State $ \st -> let (a, st') = runState sa st
in runState (f a) st'


Monad lets you sequence stateful actions together.

We also want to be able to modify this internal state, in particular we want to be able to read the current state, and replace it with a new value:

get :: State s s
get = State $ \st -> (st, st)

put :: s -> State s ()
put s = State $ \_ -> ((), s)


Now a little example:

example :: State Int String
example = do
x <- get
put (x + 1)
y <- get
put (y + 1)

pure "hello world"

main :: IO ()
main = print $ runState example 0


This prints ("hello world",2).

>>

 No.12392

>>12385
Don't try to "understand" monads, because like many other abstracts constructs, they are -semantical- definitions. That means that they allow many implementations, which differ a lot in nature. It's like trying to define a "machine", it's not really useful.

In Haskell however they have a very practical side. You can see a progression.

- Type constructor : `F a` creates a context `F` with values of type a.
- Functor: You can apply functions inside this context.
 f :: a -> b => fmap f :: F a -> F b 

- Applicative: You can use in-context functions.
 f :: a -> b => F f :: F (a -> b) => (<*>) F f :: F a -> F b 

- Monad : You can apply functions with produces contexts inside contexts
 f :: a -> F b => (=<<) f :: F a -> F b 


Given this machinery, you can see their utility. But trying to reduce these concepts to a metaphor is just restricting their nature and utility.

>>

 No.12424

>>12360
>Anything abstract can be boiled down slowly to less abstract concepts.
Like with any programming concept, it's easier to describe how the thing *operates* than explaining what it actually *is*. Defining the concept of a "function" in a concrete and exact way is what gives you the whole field of denotational semantics. Anything less is metaphorical and dishonest.

You can however explain how to use functions, what a particular function does and even how to make your own. Same goes with monads: You use them with "do"-notation or the >>= operator, they often have a clearly defined interpretation as a style of effectful computation, and defining your own requires you to define a way to "put things into the monad" and to "flatten nested monads", which can mean different things depending on your particular case.

Of course, sometimes the metaphorical handwaving can be useful for beginners. Saying "functions are sort of like mathematical functions" at least gives somewhat of an intuition how to approach them. IMHO, the best metaphor for monads is that of a recipe for an effectful computation, even though it's certainly not applicable in all cases. Read some early (but not too early) papers and tutorials from the list in >>12363.



Delete Post [ ]
[ cyb / tech / λ / layer ] [ zzz / drg / lit / diy / art ] [ w / rpg / r ] [ q ] [ / ] [ popular / ???? / rules / radio / $$ / news ] [ volafile / uboa / sushi / LainTV / lewd ]