News aggregator

How I Develop with Nix

Haskell on Reddit - Sat, 08/02/2014 - 11:31pm
Categories: Incoming News

Fantasy World Haskell

Haskell on Reddit - Sat, 08/02/2014 - 11:02pm

I recently read the following post about "Fantasy World OCaml": http://chaudhuri.info/misc/fwocaml/

This blog post details changes that the author wishes were in OCaml, both syntactic differences, library differences, build system differences, and so on.

I'm curious - what do you all think would be "Fantasy World Haskell"? What are some of the Haskell warts that you wish were fixed?

I'll start this off with a few of my pet peeves that I would currently consider:

  1. Record fields with the same name and Functor-Applicative-Monad heirarchy -- both being fixed in GHC 7.10, so maybe don't quite count.

  2. Frequent occurrence of cabal hell.

  3. The String type being used pervasively through Haskell standard library.

Things are getting a lot better quickly, so certainly these things are improving (though I'm a bit skeptical that we'll see the third point fixed any time soon, sadly...) I'm sure that many of the points y'all might think of will have been rehashed elsewhere, so if you have similar links please post them!

submitted by NiftyIon
[link] [163 comments]
Categories: Incoming News

Russell O'Connor: ICFP 2014 Post-Mortem

Planet Haskell - Sat, 08/02/2014 - 9:09pm

I participated in the 2014 ICFP programming contest this year. This year’s task was to write an AI for a simplified Pac-Man game called Lambda-Man. You could write the AI in any language you wanted, as long as it complies to a specific SECD machine architecture invented for the contest. At the end of the lightening round, it was announced that the final task included writing an AI for the ghosts as well. Again, the ghost AI could be written in any language, as long as it compiles to a separate 8-bit architecture invented for the contest.

I spent the first several hours implementing my own simulator of the arcade. Eventually I realized that I would have to start working on the AI if I was going to have an entry for the 24-hour lightening division. It was at that point I realized that the provided on-line simulator was plenty adequate for my needs and I never completed my simulator.

I have some previous experience writing assembler DSLs in Haskell to handle linking. After the 2006 ICFP contest, our team wrote a fake UM-DOS shell so that we could submit our solution in UM format. This lead me to writing an article in The Monad Reader about how to write an assembler using recursive do. After that, I encountered a really elegant and simple formulation of an assembler monad on some paste site. Unfortunately, I do not recall the author, but here is how the implementation looks.

newtype Label = Label { unLabel :: Int } data ASMMonad w a = ASMMonad { runASM :: Label -> ([w],a) } instance Monad (ASMMonad w) where return a = ASMMonad $ \_ -> ([], a) x >>= y = ASMMonad (\(Label i) -> let (o0, a) = runASM x (Label i) (o1, b) = runASM (y a) (Label (i+length o0)) in (o0 ++ o1, b)) instance MonadFix (ASMMonad w) where mfix f = ASMMonad (\i -> let (o0, a) = runASM (f a) i in (o0, a)) execASM :: ASMMonad w a -> [w] execASM m = fst $ runASM m (Label 0)

Next one adds two primitive operations. The tell function is similar to the version for the writer monad. The label function returns the current index of the output stream.

tell :: [w] -> ASMMonad w () tell l = ASMMonad $ \_ -> (l,()) label :: ASMMonad w Label label = ASMMonad $ \i -> ([],i)

Lastly one makes an ASMMonadic value for each assembly instruction

data ASM = LDC Int32 -- load constant | LD Int Int -- load variable | LDF Label -- load function | ADD {- … -} deriving Show ldc x = tell [LDC x] ld x y = tell [LD x y] ldf x = tell [LDF x] add = tell [ADD] {- … -}

At the risk of jumping ahead too far, my compiler can produce linked assembly code very simply. The clause below compiles a lambda abstraction to linked SECD assembly using recursive do.

compileH env (Abs vars body) = mdo jmp end begin <- label compileH (update env vars) body rtn end <- label ldf begin

Thanks to recursive do, the first line, jmp end, refers to the end label which is bound in the second last line.

With a DSL assembler written in Haskell, I turned to creating another DSL language in Haskell to compile to this assembly language. The SECD machine is designed for Lisp compilers, so I created a little Lisp language.

data Binding a = a := Lisp a data Lisp a = Var a | Const Int32 | Cons (Lisp a) (Lisp a) | Abs [a] (Lisp a) | Rec [Binding a] (Lisp a) {- … -}

The Abs constructor builds an n-ary lambda function. The Rec constructor plays the role of letrec to build mutually recursive references. With some abuse of the Num class and OverloadedStrings, this Lisp DSL is barely tolerable to program with directly in Haskell.

Rec [ {- … -} ,"heapNew" := ["cmp"]! (Cons "cmp" 0) -- heap layout 0 = leaf | (Cons (Cons /heap is full/ /value/) (Cons /left tree/ /right tree/)) -- "cmp" @@ ["x","y"] returns true when "x" < "y" ,"heapIsFull" := ["h"]! If (Atom "h") 1 (caar "h") ,"heapInsert" := ["cmpHeap", "v"]! Rec ["cmp" := (car "cmpHeap") ,"insert" := ["heap", "v"]! -- returns (Cons /new heap is full/ /new heap/) If (Atom "heap") (Cons (Cons 1 "v") (Cons 0 0)) (Rec ["root" := cdar "heap" ,"left" := cadr "heap" ,"right" := cddr "heap" ] $ Rec ["swap" := "cmp" @@ ["v", "root"]] $ Rec ["newRoot" := If "swap" "v" "root" ,"newV" := If "swap" "root" "v" ] $ If (caar "heap" `ou` Not ("heapIsFull" @@ ["left"])) (Rec ["rec" := "insert" @@ ["left", "newV"]] $ Cons (Cons 0 "newRoot") (Cons "rec" "right")) (Rec ["rec" := "insert" @@ ["right", "newV"]] $ Cons (Cons ("heapIsFull" @@ ["rec"]) "newRoot") (Cons "left" "rec"))) ] (Cons "cmp" ("insert" @@ [cdr "cmpHeap","v"])) {- … -}

The @@ operator is infix application for the Lisp langauge and the ! operator is infix lambda abstraction for the Lisp langauge.

This Lisp language compiles to the SECD assembly and the assembly is printed out. The compiler is very simple. It does not even implement tail call optimization. There is a bit of an annoying problem with the compiler; the assembly code is structured in exactly the same way that the original Lisp is structured. In particular, lambda abstractions are compiled directly in place, and since lambda expressions are typically not executed in the location they are declared, I have to jump over the compiled code. You can see this happening in the snippet of my compiler above. I would have preferred to write

compileH env (Abs vars body) = do fun <- proc (compileH (update env vars) body) ldf fun where proc is some function that takes an ASMMonad value and sticks the assembly code “at the end” and returns a label holding the location where the assembly code got stashed. However, I could not figure out a clever and elegent way of modifing the assembly monad to support this new primitive. This is something for you to ponder.

My Lambda AI, written in my Lisp variant, is fairly simple and similar to other entries. Lambda-Man searches out the maze for the nearest edible object. It searches down each path until it hits a junction and inserts the location of the junction into a binary heap. It also inserts the junction into a binary tree of encountered junctions. If the junction is already in the binary tree, it does not insert the junction into the heap because it has already considered it. The closest junction is popped off the heap, and the search is resumed.

There is at least one bit of surprising behaviour. If there is more than one path from one junction to another, sometimes Lambda-Man ends up taking the longer path. This behaviour did not seem to be bothersome enough to warrant fixing.

This programming task has renewed my appreciation for typed languages. The Lisp language I developed is untyped, and I made several type errors programming in it. Although it is true that I did detect (all?) my errors at run-time, they were still frustrating to debug. In a typed language, when an invariant enforced by the type system is violated, you get a compile time error that, more or less, points to the code location where the invariant is violated. In an untyped language, when an invariant is violated, you get a run-time error that, more or less, points to some point in the code where missing invariant has caused a problem. While this often is enough to determine what invariant was violated, I had little idea where the code breaking the invariant was located.

With some effort I probably could have used GADTs to bring Haskell’s type checker to the Lisp DSL, but I was not confident enough I could pull that off in time.

I also needed to write some ghost AIs. The 8-bit machine that the ghosts run on is so constrained, 256 bytes of data memory; 256 code locations; 8 registers, that it seemed to make sense to write the code in raw assembly.

The first thing I tried was to make the ghosts move randomly. This meant I needed to write my own pseudo-random number generator. Wikipedia lead me to a paper on how to write long period xorshift random number generators. The examples in that paper are all for 32-bit or 64-bit machines, but I had an 8-bit architecture. I wrote a little Haskell program to find analogous random number generators for 8-bit machines. It found 6 possibilities for 32-bit state random number generator composed of four 8-bit words that satisfied the xorshift constraints described in the paper. Here is the assembly code for getting a 2 bit pseudo-random value.

mov a,[0] div a,2 xor [0],a mov a,[0] mul a,2 xor a,[0] mov [0],[1] mov [1],[2] mov [2],[3] mul [3],8 xor [3],[2] xor [3],a ; get 2 bits mov a,[3] div a,64

The random seed is held in memory locations [0] through [3]. After moving to the successive the state, this code takes 2 pseudo-random bits from memory location [3] and puts it into register a.

I did not check the quality of this random number generator beyond constructing it so that it has a period of 232-1. I expect the bit stream to appear to be quite random.

My Lambda-Man performed reasonably well against my random ghosts, so I put some effort into making my random ghosts a little smarter. I wrote a ghost AI that tried to get above Lambda-man and attack him from above. Then I made each other ghost try to attack Lambda-man from the other three directions in the same manner. The idea is to try to trap Lambda-man between two ghosts.

These smarter ghosts were quite a bit more successful against my simple Lambda-man AI. At this point I was out of contest time, so that was it for my 2014 ICFP contest submission.

Thanks to the organizers for a terrific contest problem. I am looking forward to see the final rankings.

Categories: Offsite Blogs

easy way to plot make graphs, like matplot?

Haskell on Reddit - Sat, 08/02/2014 - 8:35pm

kinda new to haskell. im thinking something like

a = [1,2,3,4,5] b = [2,4,6,8,10]

show a b

or something like that. does it exist?

submitted by thenumber1punk
[link] [7 comments]
Categories: Incoming News

typed tagless-final interpretation examples brokenwith recent ghc

haskell-cafe - Sat, 08/02/2014 - 4:28pm
Hi all, I've been reading up on typed tagless-final interpretations [1] and the accompanying examples. It seems the stuff about CPS transformations does no longer compile, probably because of stricter typing rules. I tried both ghc 7.6 and ghc 7.8, which both give a different kind of error message. It's a bit much and long to paste here though. I would really like to get the example working, but couldn't manage by only supplying type signatures. Perhaps there is some language pragma I can turn on or off to get the old behaviour back? The 2 files needed (no further libraries needed) are: - http://okmij.org/ftp/tagless-final/course/TTF.hs (working) - http://okmij.org/ftp/tagless-final/course/CPS.hs (problem) All help would be greatly appreciated. Regards, Mathijs [1] http://okmij.org/ftp/tagless-final/course/index.html
Categories: Offsite Discussion

Minimalist GUI toolkit in GHCi

Haskell on Reddit - Sat, 08/02/2014 - 4:04pm
Categories: Incoming News

re-reading a Samson Abramsky paper ..

haskell-cafe - Sat, 08/02/2014 - 8:29am
http://staff.science.uva.nl/~ssimon/indjournal/pdf/abramsky.pdf .. no words .. I will let Samson speak for himself .. :-) Hopefully my audience cam keep up with Abramsky's terseness .. he is very "cheeky" ...
Categories: Offsite Discussion

Functional programming and William Lawvere's notion of "variable sets"(vs topos of "static sets") in a Topos ...

haskell-cafe - Sat, 08/02/2014 - 7:28am
Hello Haskellers, I have been re-reading William Lawvere's description of "variable sets" (a functor category) in "a elementary topoi" on a discrete poset/preset vs a "abstract sets" in the topos of abstract sets . In Haskell( and other FPLs .. ) aren't "pure" computations just over the topos of abstract sets and "mutable" /"time-varying/stateful" computations aren't just "variable sets" (i.e. a functor over a discrete preset-poset)?? Please forgive my bad English :-( If uncertain aboyt my Englsih, please say so. Kind regards, Vasya P.S. Yes I am familiar with Eugenio Moggi's papers on using monads for stateful computations ..
Categories: Offsite Discussion

Robin KAY: HsQML 0.3.1.1 released: One Thousand Downloads

Planet Haskell - Sat, 08/02/2014 - 5:59am
A few days ago I released HsQML 0.3.1.1, a bug fix to my Haskell binding to the Qt Quick GUI library. You can download the latest release from Hackage as usual.
The primary purpose of this release was to fix issue 20. HsQML has code which monitors variant values created using the Qt library in order to prevent objects which are referenced by a variant from being garbage collected. A flaw in this code caused it to examine the data held inside variants even when it wasn't valid, causing a crash in certain circumstances.
release-0.3.1.1 - 2014.07.31

* Fixed crash when storing Haskell objects in QML variants.
* Fixed corrupted logging output caused by threading.
In related news, HsQML has now reached over 1000 downloads from Hackage since Hackage 2 started collecting download statistics late last year. See the bar chart below:-

The spike in May was owed to the transition to Qt 5 brought about by the release of 0.3.0.0. Hopefully, the graph will climb to new heights with the release of more features in the future!
My target for the next release is to support rendering OpenGL graphics directly from Haskell code and into the QML scene, to better support applications with sophisticated requirements for custom drawing. This is tracked by issue 10.
Categories: Offsite Blogs

Proposal: add unfoldr1 to the somewhere in base

libraries list - Sat, 08/02/2014 - 12:21am
Way back in 2001, Shin-Cheng Mu proposed an unfoldr1 combinator: http://code.haskell.org/~dons/haskell-1990-2000/msg06775.html I discussed this a bit with shachaf in #haskell, and he noted that a similar function, with a slightly different but isomorphic type, appears in Edward Kmett's semigroups package as the unfoldr for NonEmpty. I propose that we add this. It can be written unfoldr1 :: (b -> (a, Maybe b)) -> b -> [a] unfoldr1 f b = go b where go b = case f b of (a, may_b) -> a : maybe [] go may_b With the appropriate RULES, it can be wrapped up in build and fuse properly. I'd love to see this written as an unfoldr instead. Does anyone know if that's possible?
Categories: Offsite Discussion

ICFP 2014 Final Call for Participation

haskell-cafe - Fri, 08/01/2014 - 10:51pm
[ Early registration ends 3 Aug; Invited speakers and conference program have been announced. ] ===================================================================== Final Call for Participation ICFP 2014 19th ACM SIGPLAN International Conference on Functional Programming and affiliated events August 31 - September 6, 2014 Gothenburg, Swedenhttp://icfpconference.org/icfp2014/ ===================================================================== ICFP provides a forum for researchers and developers to hear about the latest work on the design, implementations, principles, and uses of functional programming. The conference covers the entire spectrum of work, from practice to theory, including its peripheries. A full week dedicated to functional programming: 1 conference, 1 symposium, 10 workshops, tutorials, programming contest results, student research competition * Program: http://icfpconference.org/icfp2014/program.html * Accepted Papers: http://icfpconference.org/icfp2014/accepted.html *
Categories: Offsite Discussion

ICFP 2014 Final Call for Participation

General haskell list - Fri, 08/01/2014 - 10:50pm
[ Early registration ends 3 Aug; Invited speakers and conference program have been announced. ] ===================================================================== Final Call for Participation ICFP 2014 19th ACM SIGPLAN International Conference on Functional Programming and affiliated events August 31 - September 6, 2014 Gothenburg, Swedenhttp://icfpconference.org/icfp2014/ ===================================================================== ICFP provides a forum for researchers and developers to hear about the latest work on the design, implementations, principles, and uses of functional programming. The conference covers the entire spectrum of work, from practice to theory, including its peripheries. A full week dedicated to functional programming: 1 conference, 1 symposium, 10 workshops, tutorials, programming contest results, student research competition * Program: http://icfpconference.org/icfp2014/program.html * Accepted Papers: http://icfpconference.org/icfp2014/accepted.html *
Categories: Incoming News

EsseOS: Haskell-based tailored services for the cloud

haskell-cafe - Fri, 08/01/2014 - 6:14pm
Hi, I came across this seemingly interesting paper: EsseOS: Haskell-based tailored services for the cloud http://dl.acm.org/citation.cfm?id=2541587 which is unfortunately behind a paywall. I was wondering if someone knew about a freely accessible version of that paper, or about some project page, or just heard of it. Thank you, Thu
Categories: Offsite Discussion

haskell on Debian

haskell-cafe - Fri, 08/01/2014 - 4:43pm
I want to reinstall Haskell on Debian (in Virtualbox on Windows). So: apt-get remove haskell-platform Deleted all maps with packages in it. apt-get install haskell-platform (installing previous selected ... etc) cabal update All this without errors of warnings. cabal install cabal-install Error: /var/lib/ghc/package.conf.d: openFile: does not exist Why this error? Setup doesn't create this directory? _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe< at >haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Categories: Offsite Discussion

Douglas M. Auclair (geophf): 1HaskellADay July 2014 problems and solutions

Planet Haskell - Fri, 08/01/2014 - 3:57pm

  • July 1st, 2014: (text:) "Hi, all! @1HaskellADay problems are back! #YAY First (renewed) problem: a verbose way of saying, 'Give me a deque!' http://lpaste.net/106748" Deque, last, and all that (verbose version with hints) (solution: Deque the halls (with my solution): Data.Deque)
  • July 2nd, 2014: (text:) "Today's Haskell exercise: Vectors, length in constant time, and (bonus) reverse return in constant time. http://lpaste.net/106843" Vector (solution: Vector: Magnitude, and Direction, OH, YEAH! Data.Vector)
  • July 4th, 2014: (text:) "Today's exercise(s). pack/unpack. encode/decode. Cheer up, sweet B'Genes! http://lpaste.net/106912" Cheer up, Sweet B'Genes (solution: GATTACA)
  • July 7th, 2014: (text:) "#haskell daily exercise: ROLL with it, Baby! http://lpaste.net/107047  ('cause I'm feeling a little #forth'y')" Roll (solution: Rollin' on the (finite) river)
  • Bonus problem: July 7th, 2014: (text:) "For those who found the 'roll'-exercise trivial; here's (a more than) a bit more of a challenge for you to play with. http://lpaste.net/107023" Acid rules! (solution: "A solution set to today's challenge exercise: BASIC ... http://lpaste.net/107069  ... and Acidic http://lpaste.net/107071  ... WHEW! That was fun!" BASIC ... and Acitic)
  • July 8th, 2014: (text:) "Today's #Haskell exercise: LOTTO! Powerball! Mega-whatever! Who's the big winner? http://lpaste.net/107104" Lotto (solution: "And the big winner today is ... solution-set to today's #Haskell lotto exercise http://lpaste.net/107130" ... and the winner is ...)
  • Bonus problem: July 8th, 2014: (text:) "#bonus #haskell exercise: Well, that was RND... Randomness, and such (or 'as such') http://lpaste.net/107105" Well, that was RND (solution: For YESTERDAY's bonus question of roll-your-own-rnd-nbr-generator, here's one as comonadic cellular automata (*WHEW*) http://lpaste.net/107205: Data.Random)
  • July 9th, 2014: (text:) "Okay, ... WHERE did yesterday and today GO? :/ #haskell exercise today: "Hey, Buddy!" http://lpaste.net/107181  I will post solution in 4 hours" Hey, Buddy! Distinct sets-of-an-original-set. (solution: "Here's a story ..." A(n inefficient) solution to bunches and cliques. http://lpaste.net/107273" Brady Bunch)
  • July 10th, 2014: (text:) "Today's #haskell list-exercise: "Get out of the pool!" http://lpaste.net/107286  Will post a solution at 9 pm EDT (which is what time CET? ;)" (solution: "She's a supa-freak! She's supa-freaky! (Bass riff) A solution to today's #haskell exercise about list-length-ordering http://lpaste.net/107308")
  • July 11th, 2014: (text:) ""It's Friday, Friday!" So, does that mean Rebecca Black wants to code #haskell, too? Today is a Calendar #exercise http://lpaste.net/107328" (solution: ""In a New York Minute": a solution to today's #haskell exercise that took WAAAY more than a minute to complete! #WHEW http://lpaste.net/107370")
  • July 14th, 2014: (text:) "Today's #haskell exercise: isPrime with some numbers to test against. They aren't even really Mp-hard. ;) http://lpaste.net/107463" First stab at primality-test (solution: "A simple, straightforward stab at the test for primality. #haskell #exercise http://lpaste.net/107483" The start of a primal inquiry
  • July 15th, 2014: (text:) "Primes and ... 'not-primes.' For a prime, p, a run of p-consecutive 'plain' numbers is today's #haskell exercise: http://lpaste.net/107536" (solution: "So ya gotta ask yerself da question: are ya feelin' lucky, punk? Run of p non-primes in linear time http://lpaste.net/107549  #haskell exercise." Alternate solution by Gautier: http://lpaste.net/107549)
  • July 16th, 2014: (text:) "Difference lists? We no need no steenkin' Difference lists!" http://lpaste.net/107593  DList in #haskell for today's exercise. (solution: "DLists? We got'cher DList right here! A solution to today's #haskell exercise is posted at http://lpaste.net/107607")
  • July 17th, 2014 (text:) "http://lpaste.net/107652 Prélude à l'après-midi d'un Stream ... I thought that last word was ... something else...? #haskell exercise today." Comonads for lists and Id. (solution: "Control.Comonad: That was easy! http://lpaste.net/107661 #haskell exercise #solution" Learn you a Comonad for Greater GoodFunny story, bro'! id is not necessarily Id. (I knew that.) http://lpaste.net/107662 #haskell solution")
  • Bonus exercise: July 17th, 2014 (text:) "Streams are natural, streams are fun, streams are best when ... THEY'RE BONUS QUESTIONS! #bonus #haskell exercise http://lpaste.net/107655" LET'S GET THIS PARTY STARTED! (solution: "Take this Stream and ... it! #solution to today's #haskell #bonus exercises http://lpaste.net/107665")
  • July 18th, 2014: (text: "Today's #haskell exercise: Frère Mersenne would like a prime, please. http://lpaste.net/107700") (see solution next bullet)
  • Bonus exercise: July 18th, 2014 (text: "#bonus prime-time! Frère Mersenne would be pleased with a partial proof of a prime ... in good time. http://lpaste.net/107701") (solution: "A #haskell #solution for (monadic?) primes and the #bonus interruptible primes. http://lpaste.net/107708") Primary primes.
  • Bonus-bonus exercise: July 18th, 2014 (text: "Ooh! π-charts! No. Wait. #bonus-bonus #haskell exercise. http://lpaste.net/107702") (solution: "#bonus-bonus: a #solution http://lpaste.net/107718")


  • July 21st, 2014: (text: "Demonstrating coprimality of two integers with examples #haskell exercise http://lpaste.net/107819") (solution: "A coprimes solution #haskell problem is at http://lpaste.net/107843")
  • July 22nd, 2014: (text: "The prime factors of a number (and grouping thereof) as today's #haskell exercise. http://lpaste.net/107878") (solution: "OKAY, THEN! Some prime factors for ya, ... after much iteration (torquing) over this #haskell exercise solution. http://lpaste.net/107939")
  • Bonus exercise: July 22nd, 2014: ("For today's #bonus #haskell exercise you'll find a Bag 'o gold at the end of the rainbow http://lpaste.net/107881") (solution: "Second things first: a definition for the Bag data type as today's #bonus #haskell exercise. http://lpaste.net/107815")
  • July 23rd, 2014: (text: "Today's #haskell exercise, two variations of Euler's totient function http://lpaste.net/107955") (solution: "And, for a very small φ ... http://lpaste.net/107972  is a solution-set to today's #haskell exercise.")
  • July 24th, 2014: (text: "WEAKSAUCE! Goldbach's conjecture irreverently presented as a #haskell exercise. http://lpaste.net/108019") (solution: "That solution to today's #haskell exercise will cost you one Goldbach (*groan!*) http://lpaste.net/108059")
  • July 25th, 2014: LOGIC! Peano series: it's as easy as p1, p2, p3 ... http://lpaste.net/108099 ... in today's #haskell exercise. "Excuse me, Miss, where do we put this Grande Peano?" A solution to today's #Haskell exercise in the HA!-DSL http://lpaste.net/108140
  • Bonus: July 25th, 2014: http://lpaste.net/108108 Bonus #haskell problem for today. But not as easy as λa, λb, λc ... Church numerals and booleans. Correction: Ooh! forall! Church encodings and Haskell have a funny-kind of relationship. Updated the #bonus #haskell exercise with rank-types and forall. Solution: "Gimme that olde-time Church encoding ... it's good enough for me!" A solution to today's #bonus #haskell exercise http://lpaste.net/108114
  • July 28th, 2014: George Boole, I presume? Today's #haskell exercise: http://lpaste.net/108272. Solution: This and-or That ... a NAND-implementation of today's #haskell exercise at http://lpaste.net/108295
  • July 29th, 2014: Readin' 'Ritin' 'Rithmetic: today's #haskell exercise http://lpaste.net/108358 Solution: That's alotta NANDs! A solution to today's exercise at http://lpaste.net/108387
  • July 30th, 2014: ACHTUNG! BlinkenLights! Today's #haskell exercise http://lpaste.net/108420. Solution: Let it Snow! Let it Snow! Let it (binary) Snow! A solution to today's exercise is at http://lpaste.net/108429 
  • July 31st, 2014: π-time! http://lpaste.net/108485 Today's #haskell exercise. BLARG! UPDATE! Please read the update attached to the problem statement, simplifying the calculation quite a bit: http://lpaste.net/108485 Solution: Apple or coconut π? A solution to today's problem http://lpaste.net/108494

Notes on the problems
  • July 9th, 2014. I didn't quite know how to go about this, so I made several attempts with the State pattern. But how to describe it? It's the base pool from which you draw, and each (sub-)choice-point affects it, what's that type? I spent way too much time trying to discern the type, and failing. But now, a much simpler approach suggests itself to me (after experiencing the New York Minute exercise): this is simply a permutation of the list, and then that permutation is partitioned by the sizes of the groups! Implementing permute-then-partition is a much simpler approach than tracking some monster monadic state transformer.

    No, that didn't work, either. A permutation will give you [[1,2], ...] and[[2,1], ...] That is, all solutions, even the redundant ones. So, I reworked the problem simply following the data. With takeout feeding the iterative-deepening function, I finally got a guarded state-like thingie working fast and correctly. The new solution is on the same page as the old one.
  • July 11th, 2014. The New York Minute problem demonstrates the implementation of a rule-based classifer. It takes unclassified numeric inputs, and based on the cues from the rules, either types each number into day, month, year, hour, minute, or rejects the input data as unclassifiable. I was pleased to have implemented this entire system in less than two days of work! Sweet!
  • July 22nd, 2014. So, I've been running up against the double-exponential cost of computing a stream of primes for some time now since I gave the solution to the question of demonstrating the Prime Number Theorem. So now I have to tackle of bringing down that extraordinary, or unreasonable, cost down to something useable, and along those lines (of feasibility), I'm thinking of instead of regenerating and re-searching the primesish stream that we have some kind of State-like thing of ([already generated primes], indexed-primesish) ... something like that. Solution: "General improvement of problem-solving modules in anticipation of solving today's #haskell exercise, including primes: http://lpaste.net/107480"
Categories: Offsite Blogs

Haskell and IO monads

Haskell on Reddit - Fri, 08/01/2014 - 2:09pm

Hey there,

having a list of names of files or folders I'm trying to do the following:

given an (x:xs), if x is a directory, get his content and add it to the list. If x is a file read it.

This is what I'm trying to do:

yascc :: [String] -> IO() yascc (x:xs) = do isDir <- doesDirectoryExist x if isDir then content <- getDirectoryContent x

The rest of the code is not provided because I get a syntactic error in the last line. What is the correct way of doing this?(Not asking for code)

Thank you.

submitted by The_Floyd
[link] [12 comments]
Categories: Incoming News

Edward Kmett: Letter to a Young Haskell Enthusiast

Planet Haskell - Fri, 08/01/2014 - 1:44pm

The following letter is not about what "old hands" know and newcomers do not. Instead, it is about lessons that we all need to learn more than once, and remind ourselves of. It is about tendencies that are common, and understandable, and come with the flush of excitement of learning any new thing that we understand is important, and about the difficulty, always, in trying to decide how best to convey that excitement and sense of importance to others, in a way that they will listen. It is written more specifically, but only because I have found that if we don't talk specifics as well as generalities, the generalities make no sense. This holds for algebraic structures, and it holds for other, vaguer concepts no less. It is a letter full of things I want to remember, as well as of advice I want to share. I expect I will want to remind myself of it when I encounter somebody who is wrong on the internet, which, I understand, may occur on rare occasion.

You’ve recently entered the world of strongly typed functional programming, and you’ve decided it is great. You’ve written a program or two or a library or two, and you’re getting the hang of it. You hop on IRC and hear new words and ideas every day. There are always new concepts to learn, new libraries to explore, new ways to refactor your code, new typeclasses to make instances of.

Now, you’re a social person, and you want to go forth and share all the great things you’ve learned. And you have learned enough to distinguish some true statements from some false statements, and you want to go and slay all the false statements in the world.

Is this really what you want to do? Do you want to help people, do you want to teach people new wonderful things? Do you want to share the things that excite you? Or do you want to feel better about yourself, confirm that you are programming better, confirm that you are smarter and know more, reassure yourself that your adherence to a niche language is ok by striking out against the mainstream? Of course, you want to do the former. But a part of you probably secretly wants to do the latter, because in my experience that part is in all of us. It is our ego, and it drives us to great things, but it also can hold us back, make us act like jerks, and, worst of all, stand in the way of communicating with others about what we truly care about.

Haskell wasn’t built on great ideas, although it has those. It was built on a culture of how ideas are treated. It was not built on slaying others’ dragons, but on finding our own way; not tearing down rotten ideas (no matter how rotten) but showing by example how we didn’t need those ideas after all.

In functional programming, our proofs are not by contradiction, but by construction. If you want to teach functional programming, or preach functional programming, or just to even have productive discussions as we all build libraries and projects together, it will serve you well to learn that ethic.

You know better than the next developer, or so you think. This is because of something you have learned. So how do you help them want to learn it too? You do not tell them this is a language for smart people. You do not tell them you are smart because you use this language. You tell them that types are for fallible people, like we all are. They help us reason and catch our mistakes, because while software has grown more complex, we’re still stuck with the same old brains. If they tell you they don’t need types to catch errors, tell them that they must be much smarter than you, because you sure do. But even more, tell them that all the brainpower they use to not need types could turn into even greater, bigger, and more creative ideas if they let the compiler help them.

This is not a language for clever people, although there are clever things that can be done in this language. It is a language for simple things and clever things alike, and sometimes we want to be simple, and sometimes we want to be clever. But we don’t give bonus points for being clever. Sometimes, it’s just fun, like solving a crossword puzzle or playing a tricky Bach prelude, or learning a tango. We want to keep simple things simple so that tricky things are possible.

It is not a language that is “more mathematical” or “for math” or “about math”. Yes, in a deep formal sense, programming is math. But when someone objects to this, this is not because they are a dumb person, a bad person, or a malicious person. They object because they have had a bad notion of math foisted on them. “Math” is the thing that people wield over them to tell them they are not good enough, that they cannot learn things, that they don’t have the mindset for it. That’s a dirty lie. Math is not calculation — that’s what computers are for. Nor is math just abstract symbols. Nor is math a prerequisite for Haskell. If anything, Haskell might be what makes somebody find math interesting at all. Our equation should not be that math is hard, and so programming is hard. Rather, it should be that programming can be fun, and this means that math can be fun too. Some may object that programming is not only math, because it is engineering as well, and creativity, and practical tradeoffs. But, surprisingly, these are also elements of the practice of math, if not the textbooks we are given.

I have known great Haskell programmers, and even great computer scientists who know only a little linear algebra maybe, or never bothered to pick up category theory. You don’t need that stuff to be a great Haskell programmer. It might be one way. The only thing you need category theory for is to take great categorical and mathematical concepts from the world and import them back to programming, and translate them along the way so that others don’t need to make the same journey you did. And you don’t even need to do that, if you have patience, because somebody else will come along and do it for you, eventually.

The most important thing, though not hardest, about teaching and spreading knowledge is to emphasize that this is for everyone. Nobody is too young, too inexperienced, too old, too set in their ways, too excitable, insufficiently mathematical, etc. Believe in everyone, attack nobody, even the trolliest.* Attacking somebody builds a culture of sniping and argumentativeness. It spreads to the second trolliest, and soforth, and then eventually to an innocent bystander who just says the wrong thing to spark bad memories of the last big argument.

The hardest thing, and the second most important, is to put aside your pride. If you want to teach people, you have to empathize with how they think, and also with how they feel. If your primary goal is to spread knowledge, then you must be relentlessly self-critical of anything you do or say that gets in the way of that. And you don’t get to judge that — others do. And you must just believe them. I told you this was hard. So if somebody finds you offputting, that’s your fault. If you say something and somebody is hurt or takes offense, it is not their fault for being upset, or feeling bad. This is not about what is abstractly hurtful in a cosmic sense; it is about the fact that you have failed, concretely, to communicate as you desired. So accept the criticism, apologize for giving offense (not just for having upset someone but also for what you did to hurt them), and attempt to learn why they feel how they feel, for next time.

Note that if you have made somebody feel crummy, they may not be in a mood to explain why or how, because their opinion of you has already plummeted. So don’t declare that they must or should explain themselves to you, although you may politely ask. Remember that knowledge does not stand above human behavior. Often, you don't need to know exactly why a person feels the way they do, only that they do, so you can respect that. If you find yourself demanding explanations, ask yourself, if you knew this thing, would that change your behavior? How? If not, then learn to let it go.

Remember also that they were put off by your actions, not by your existence. It is easy to miss this distinction and react defensively. "Fight-or-flight" stands in the way of clear thinking and your ability to empathize; try taking a breath and maybe a walk until the adrenaline isn't derailing your true intentions.

Will this leave you satisfied? That depends. If your goal is to understand everything and have everybody agree with regards to everything that is in some sense objectively true, it will not. If your goal is to have the widest, nicest, most diverse, and most fun Haskell community possible, and to interact in an atmosphere of mutual respect and consideration, then it is the only thing that will leave you satisfied.

If you make even the most modest (to your mind) mistake, be it in social interaction or technical detail, be quick to apologize and retract, and do so freely. What is there to lose? Only your pride. Who keeps track? Only you. What is there to gain? Integrity, and ultimately that integrity will feel far more fulfilling than the cheap passing thrills of cutting somebody else down or deflecting their concerns.

Sometimes it may be, for whatever reason, that somebody doesn’t want to talk to you, because at some point your conversation turned into an argument. Maybe they did it, maybe you did it, maybe you did it together. It doesn’t matter, learn to walk away. Learn from the experience how to communicate better, how to avoid that pattern, how to always be the more positive, more friendly, more forward-looking. Take satisfaction in the effort in that. Don’t talk about them behind their back, because that will only fuel your own bad impulses. Instead, think about how you can change.

Your self-esteem doesn’t need your help. You may feel you need to prove yourself, but you don't. Other people, in general, have better things to do with their time than judge you, even when you may sometimes feel otherwise. You know you’re talented, that you have learned things, and built things, and that this will be recognized in time. Nobody else wants to hear it from you, and the more they hear it, the less they will believe it, and the more it will distract from what you really want, which is not to feed your ego, not to be great, but to accomplish something great, or even just to find others to share something great with. In fact, if anyone's self-esteem should be cared for, it is that of the people you are talking to. The more confident they are in their capacity and their worth, the more willing they will be to learn new things, and to acknowledge that their knowledge, like all of ours, is limited and partial. You must believe in yourself to be willing to learn new things, and if you want to cultivate more learners, you must cultivate that self-belief in others.

Knowledge is not imposing. Knowledge is fun. Anyone, given time and inclination, can acquire it. Don’t only lecture, but continue to learn, because there is always much more than you know. (And if there wasn’t, wow, that would be depressing, because what would there be to learn next?) Learn to value all opinions, because they all come from experiences, and all those experiences have something to teach us. Dynamic typing advocates have brought us great leaps in JIT techniques. If you’re interested in certain numerical optimizations, you need to turn to work pioneered in C++ or Fortran. Like you, I would rather write in Haskell. But it is not just the tools that matter but the ideas, and you will find they come from everywhere.

In fact, we have so much to learn that we direct our learning by setting up barriers — declaring certain tools, fields, languages, or communities not worth our time. This isn’t because they have nothing to offer, but it is a crutch for us to shortcut evaluating too many options all at once. It is fine, and in fact necessary, to narrow the scope of your knowledge to increase its depth. But be glad that others are charting other paths! Who knows what they will bring back from those explorations.

If somebody is chatting about programming on the internet, they’re already ahead of the pack, already interested in craft and knowledge. You may not share their opinions, but you have things to learn from one another, always. Maybe the time and place aren’t right to share ideas and go over disputes. That’s ok. There will be another time and place, or maybe there won’t be. There is a big internet full of people, and you don’t need to be everybody’s friend or everybody’s mentor. You should just avoid being anybody’s enemy, because your time and theirs is too precious to waste it on hard feelings instead of learning new cool stuff.

This advice is not a one-time proposition. Every time we learn something new and want to share it, we face these issues all over again -- the desire to proclaim, to overturn received wisdom all at once -- and the worse the received wisdom, the more vehemently we want to strike out. But if we are generous listeners and attentive teachers, we not only teach better and spread more knowledge, but also learn more, and enjoy ourselves more in the process. To paraphrase Rilke’s “Letter to a Young Poet”: Knowledge is good if it has sprung from necessity. In this nature of its origin lies the judgement of it: there is no other.

Thanks to the various folks in and around the Haskell world who have helped me refine this article. I don't name you only because I don't want to imply your endorsement, or give what is still, at base, a very personal take, any particular sort of imprimatur of a broader group of people, all of whom I suspect will disagree among themselves and with me about various specifics.

*: It has been pointed out to me that this advice is not universal. Clearly there are some things that deserve more pointed responses. Bigotry, outright harassment and poisonous behavior, etc. So please read this paragraph only as it applies to talking about technical issues, not as regards to many other things, where there are people better equipped than me to give advice.

Categories: Offsite Blogs