News aggregator

Generalized null / zero

haskell-cafe - Wed, 01/29/2014 - 4:25am
1. Is there a more general version of `null`? (e.g. for a Monad, Functor, Applicative, Traversable or the like.) The closest I can come up with is, in decreasing clunkiness: zero :: (MonadPlus m, Eq (m a)) => m a -> Bool zero = m == mzero zero :: (Alternative f, Eq (f a)) => f a -> Bool zero = m == empty zero :: (Monoid m, Eq m) => m -> Bool zero = m == mempty Though requiring Eq seems ugly and unnecessary, in theory. 2. In that vein, is there an existing function for "a value or a default if it's zero"? E.g.: orElse :: (Monoid m) => m -> m -> m a `orElse` b = if zero a then b else a Thank you, Alvaro http://alva.ro _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe< at >haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Categories: Offsite Discussion

[ANN] yocto-0.1.2

General haskell list - Tue, 01/28/2014 - 9:57pm
Howdy, I'd like to present a minimal JSON encoding/decoding library: http://hackage.haskell.org/package/yocto-0.1.2 From the README: Yocto is exceedingly simple: it only exports one type, Value (which can represent any JSON-encoded data) in addition to Read and Show instances for it--which, respectively, take care of decoding and encoding values automatically. It's worth mentioning that Yocto handles numbers as Rationals rather than Doubles, which makes it faithful to the JSON standard and lets it handle rational numbers of arbitrary magnitude and precision. The name is a play on metric unit prefixes: AttoJson is a tiny JSON library, and Yocto is even smaller. (The entire implementation fits in fewer than 80 lines x 80 columns.) [It is meant primarily for interactive use and one-offs, which is how I'm handwaving hijacking Read and Show.] Anyway, I hope you find it useful; the code lives here: https://github.com/ajg/yocto Alvaro http://alva.ro _______________________________________________ Hask
Categories: Incoming News

Lazy MWC Random?

haskell-cafe - Tue, 01/28/2014 - 8:08pm
Dear Haskellers, I'm in a situation where I'd like to generate an infinite list of random elements (basically, I'm simulating stochastic systems). I feel like MWC Random is the fastest RNG available, but when I try to pull the infinite list out of RandST, it obviously doesn't halt, because ST is strict. Someone posted a way around this in this stack overflow thread: https://stackoverflow.com/questions/16248600/parallel-computations-with-fast-randomness-and-purity Which would fix my problem. My question is though, why isn't ST.Lazy included as a PrimMonad instance anyway? The best answer I can come up with is that, since evaluating the Generator is time dependent, it's best to make it strict to make sure that one's program isn't tapping into /dev/random at arbitrary times. In this way the best stackoverflow solution is quite good. It requires one to strictly generate a Seed (since that's the only way to do it), but then converts the ST Monad to the Lazy version to Lazify everything else. Howeve
Categories: Offsite Discussion

Alejandro Cabrera: 10 Ways to Incorporate Haskell into a Modern, Functional, CS Curriculum

Planet Haskell - Tue, 01/28/2014 - 7:25pm
I had some time to spare while I was waiting for dinner to be ready. Dinner was being prepared by the local China Gate, and it would probably take on the order of 10 to 15 minutes. So I sat down in the lobby with a notepad in hand.

The topic on my thoughts: how could Haskell be incorporated into a modern CS curriculum? I decided to run as radically as I could with this, writing a rough draft of what such a curriculum might look like.

I won't make any arguments for or against functional programming here. I refer readers instead to papers like this one and this one, talks like this one or this one, and books like this one. This is an exercise in ideation.

Without further ado, let's begin:

0. Haskell for Introductory Computer Science

Imagine this is the first time you're learning programming. You've never been exposed to mutation, to functions, to compiling, algorithms, or any of the details of architecture. Where do we start?

Four weeks of Haskell. Enough to get through the first few chapters of LYAH and be able to start thinking about recursion. End each week with a simple exercise, for example, upper-casing a list of strings, upper-casing only the first letter of every string that is longer than 2 characters - little things to build confidence. The Udacity Introduction to Computer Science course has many appropriate ideas for beginning level exercises.

With that introductory period out of the way, now's the time to show why computer science is relevant! Take the time to show case the areas: operating systems, networking, algorithms, programming languages, cryptography, architecture, hardware, and more. Make it relevant:

* Operating systems: Why are there so many? What does it do? How does my application (email, browser, Steam) run from beginning to end?
* Algorithms: How do you figure out if two characters have collided in a video game? How do you sort a list of address contacts alphabetically by last name?
* Networking: How do you send an instant message or an email to a friend on the other side of the world?
* Programming Languages: As with operating systems.

There are many applicable introductory exercises here that can set the pace for future courses.

1. Haskell for Basic Algorithms

This one, and the latter algorithms course on this "Top 10 List", deserve special attention.

Algorithms are fundamentally pure constructs. You give them a well-defined input, and receive a well-defined output

Take plenty of time to provide weekly exercises. Teaching sorting algorithms, trees, string matching algorithms, and more will be a delight here, I predict.

It's also a good time to introduce basic run-time analysis, e.g., Big O notation.

This is also a beautiful time to introduce QuickCheck in conjunction with invariants.

2. Haskell for Data Structures

Very similar to the basic algorithms course, except now we teach students about some basic ways to organize data. Lists, vectors, trees, hash maps, and graphs - these should be enough to keep most students (and practitioners) well-equipped for years!

QuickCheck and frequent programming exercises will do well here.

If an advanced version of this course is desired, I highly recommend starting from here to brainstorm a variant: Purely Functional Data Structures

3. Haskell for Networking

This can be very low-level (OSI network stack, TCP window buffering, etc.), it can be very high-level (HTTP, distributed systems), or some mix of the two.

I think the most important concepts students can come of this course with would be:

* Validating data at the boundaries and the dangers/usefulness of IO
* How to communicate with other systems
* How to write their own protocols, and why in general, they shouldn't reinvent the wheel

4. Haskell for Operating Systems

Teach them to ask - what is an operating system? How do I manage my resources?

It's worth surveying the concepts of: memory management, file systems, data persistence, concurrency, parallelism, process management, task scheduling, and possibly a bit more.

Great projects in this course include: 1) write your own shell, 2) write a simple, local task manager.

5. Haskell for Comparative Programming Languagues

Let's talk types, functions, composition, and problem solving using different approaches. Ideally, such a course would come after learning how to design solutions to mid-sized programming challenges.

After that, have students write an interpreter for a Lisp.

6. Haskell for Compiler Construction

More on: write your own language. This course should cover parsing, lexical analysis, type analysis, and the conversion from source to assembly.

7. Haskell for Advanced Algorithms

This one's going to be fun. Unleash the power of equational reasoning to put together a course that runs through: graph theory, network flow analysis, greedy algorithms, memoization, and more.

This would also be a great time to discuss how the price one pays for purity in regards to asymptotic performance, and how to overcome that, if necessary.

Also, an extended treatment of algorithmic analysis in the presence of laziness would be valuable here.

8. Haskell for Introductory Design of Programs

Really, this should be higher up in this list, and a very early course.

The goal of this course is to come out of it knowing how to:

* Get a big picture of what they're trying to build
* Break it down into the smaller pieces
* Iterate 'til they get the big picture running

It's a great time to teach some basic ideas for testing, how to experiment with the REPL, and how to take advantage of the type system for simple things.

On a more social level, it's a wonderful time to also guide students towards collaborative design, e.g., how to work together and make it fun and efficient.

9. Haskell for High-Performance Computing

This could be a very fun course. It affords the opportunity to allow students to run wild with simulations and experiments of their choosing, while learning about what it means to do high-performance computing in a functional language.

Given that, it should teach some basic tools that will be applicable to most or all projects. How does one benchmark well? What are the evils of optimization? What is over-optimization? When is optimization needed? What tools exist right now to harness parallelism in Haskell (Repa, Accelerate, etc.)? When is data distribution needed? Why is parallelism important? How is parallelism different than concurrency? How can the type system be wielded to help keep units (km/s, etc.) consistent across calculations?

I'd advocate for letting students choose their own projects built in parallel with the course taking place. A simple default is to optimize the much-lauded matrix multiply to larger and larger scales (distributed even, if they want to go so far!). Writing a collision detection engine for a simple game would be pretty interesting, as well.

Notably (in my opinion) absent topics:

* Hardware: CPUs, cache hierarchies, main memory, storage, interconnects
* Advanced data structures
* Cryptography
* Web development
* Type systems
* Cross-disciplinary development, e.g., Haskell for CS + [Physics, Chemistry, Biology, etc.]

These topics are absent from my list for no reason other than I didn't think of them 'til the list was done and articulated. There's so much one can learn and apply at the level of abstraction that computer science (and mathematics) affords that we could specialize further and further. For my own sake, I'm setting a limit. :)

Final Notes

I've just brain-stormed a curriculum in Haskell. There's a lot of details missing, but it's a working draft.

There's also other things to consider, beyond the technical aspects. Consider the social aspects. How we teach students to work together? How do we keep learning engaging and fun?  How do we help students connect to the greater community of developers that exist outside of academia? How do we keep the lessons relevant to the lives that they lead? How do we encourage them to pursue their passions?
Categories: Offsite Blogs

www.huffingtonpost.com

del.icio.us/haskell - Tue, 01/28/2014 - 6:35pm
Categories: Offsite Blogs

www.cs.uu.nl

del.icio.us/haskell - Tue, 01/28/2014 - 6:35pm
Categories: Offsite Blogs

www.huffingtonpost.com

del.icio.us/haskell - Tue, 01/28/2014 - 6:35pm
Categories: Offsite Blogs

www.cs.uu.nl

del.icio.us/haskell - Tue, 01/28/2014 - 6:35pm
Categories: Offsite Blogs

manage effects in a DSL

haskell-cafe - Tue, 01/28/2014 - 1:03pm
Hi Haskell-Caféists! I have a small DSL for a game. Some instructions have effects (change the game state), some not. -> In short, my question is: how can I semantically separate instructions with effect from the others? i.e. how can I mark down and track those effects? Here is a simplified version of the DSL I use. First some boilerplate: This is the DSL: It can read and write to an account (belonging to the state of the game), set a victory condition, and trigger some event every minute. With that you can write: "victoryRule" sets the victory condition to be: "if there is more than 100 gold in the account, you win." This is the game state: The evaluation of "Exp" can be: If you evaluate "victoryRule", you change the Game state by setting the victory field. Then, each time you will evaluate the victory field, you will know if you won or not (depending on your account...). This is all well and good, but imagine if you write: Ho no! Now each time a player is refreshing his screen (on the web
Categories: Offsite Discussion

Munich Haskell Meeting

haskell-cafe - Tue, 01/28/2014 - 12:52pm
Dear all, I hope that you had good start into 2014. Munich's Haskell enthusiasts (or other declarative languages) meet for their first get-together in 2014 on Thu, 30th of January at 19h30 at Cafe Puck. If you plan to join, please go here and hit the button: http://www.haskell-munich.de/dates With my best wishes for this year, Heinrich
Categories: Offsite Discussion

To LLVM or not to LLVM...

haskell-cafe - Tue, 01/28/2014 - 12:10pm
A package I just released (arb-fft) gets about a 17% performance boost from using GHC's LLVM backend (on my machine at least). That seems a big enough gain that I put "-fllvm" into the ghc-options field in the Cabal file for the package. Unfortunately, that means the package won't install unless you have the LLVM tools installed. What's the best thing to do? Use the native code generator by default and add a Cabal flag to install using LLVM? Just take the "-fllvm" out and add a note to the Cabal file description to tell people to install using LLVM if they have it? A quick survey of packages on Hackage reveals only very few instances where the "-fllvm" flag appears in Cabal files, which makes me suspect that I'm doing it wrong.
Categories: Offsite Discussion

Manage effects in a DSL

Haskell on Reddit - Tue, 01/28/2014 - 6:08am

Hi Haskellers! I have a small DSL for a game. Some instructions have effects (change the game state), some not. -> In short, my question is: how can I semantically separate instructions with effect from the others? i.e. how can I mark down and track those effects?

Here is a simplified version of the DSL I use. First some boilerplate (this is literate Haskell):

> {-# LANGUAGE GADTs #-} > import Control.Monad > import Control.Monad.State > import Control.Monad.Free

This is the DSL:

> data Exp a where > ReadAccount :: Exp Int > WriteAccount :: Exp Int -> Exp () > SetVictory :: Exp Bool -> Exp () > OnTimer :: Exp () -> Exp () > Return :: a -> Exp a > Bind :: Exp a -> (a -> Exp b) -> Exp b

It can read and write to an account (belonging to the state of the game), set a victory condition, and trigger some event every minute.

> instance Monad Exp where > return = Return > (>>=) = Bind > instance Functor Exp where > fmap f e = Bind e $ Return . f

With that you can write:

> victoryRule :: Exp () > victoryRule = SetVictory $ do > m <- ReadAccount > return (m > 100)

"victoryRule" sets the victory condition to be: "if there is more than 100 gold in the account, you win."

This is the game state:

> data Game = Game { bankAccount :: Int, > victory :: Exp Bool, > timerEvent :: Exp ()}

The evaluation of "Exp" can be:

> eval :: Exp a -> State Game a > eval (SetVictory v) = modify (\g -> g{victory = v}) > eval ReadAccount = get >>= return . bankAccount > eval _ = undefined -- etc.

If you evaluate "victoryRule", you change the Game state by setting the victory field. Then, each time you will evaluate the victory field in Game, you will know if you won or not (depending on your account...). This is all well and good, but imagine if you write:

> victoryRule' :: Exp () > victoryRule' = SetVictory $ do > m <- ReadAccount > WriteAccount (return $ m + 1) > return (m > 100)

Ho no! Now each time a player is refreshing his screen (on the web interface), the victory condition is re-evaluated to be displayed again, and the bank account is increased by 1! This is not what we want. We should allow only effect-less (pure) instructions in the victory field, like readAccount, but not WriteAccount.

How would you do that?

I tried with the Free monad to delimit those effects. I re-write each primitives, marking them with the special type "Effect", when needed.

> type Effect = Free Exp > -- readAccount remain the same: it has no effect > readAccount :: Exp Int > readAccount = ReadAccount > --writeAccount is marked as having an effect > writeAccount :: Exp Int -> Effect (Exp ()) > writeAccount ei = Pure $ WriteAccount ei > --onTimer is able to trigger an effect every minute > onTimer :: Effect (Exp ()) -> Effect (Exp ()) > onTimer e = Pure $ OnTimer $ iter join e > --victoryRule can be re-written like this, note that effects are rejected now > victoryRule'' :: Effect (Exp ()) > victoryRule'' = Pure $ SetVictory $ do > m <- readAccount > --writeAccount (return $ m + 1) --will be rejected at compile time (good)! > return (m > 100) > --increase my bank account by 1 every minute > winMoney :: Effect (Exp ()) > winMoney = onTimer $ do > m <- lift readAccount > writeAccount (return $ m + 1)

I don't know if I got it right at all... How does it sound? It only bothers me that in this context "Pure" really means "Impure" :) Do you think of any other solution?

Cheers, Corentin

submitted by kaukau
[link] [16 comments]
Categories: Incoming News

Lecture notes and assignments

del.icio.us/haskell - Tue, 01/28/2014 - 3:07am
Categories: Offsite Blogs

Lecture notes and assignments

del.icio.us/haskell - Tue, 01/28/2014 - 3:07am
Categories: Offsite Blogs

Yesod Web Framework: Announcing: the Resource monad

Planet Haskell - Tue, 01/28/2014 - 2:40am

Back in June, Gabriel Gonzalez wrote a blog post on the Resource monad. At the time, I thought it was an interesting idea, but I didn't have a very good use case for it. However, while working on Persistent 2.0, I realized it was a great way to abstract the concept of acquiring a database connection, and allow both ResourceT and non-ResourceT access to Persistent.

So with Gabriel's permission to steal his idea, I added the Resource monad to the resourcet package. The internal representation is slightly different than the one presented in Gabriel's blog post. In order to provide proper async exception safety, the internal structure is:

data Allocated a = Allocated !a !(IO ()) newtype Resource a = Resource ((forall b. IO b -> IO b) -> IO (Allocated a)) instance Monad Resource where return a = Resource (\_ -> return (Allocated a (return ()))) Resource f >>= g' = Resource $ \restore -> do Allocated x free1 <- f restore let Resource g = g' x Allocated y free2 <- g restore `E.onException` free1 return $! Allocated y (free2 `E.finally` free1)

Allocated provides a value and its cleanup method. Resource is a function from mask's restore function to an action returning Allocated. By being set up in this way, we know that async exceptions are not thrown in the intermediate steps of monadic bind.

Usage of the API is pretty simple. We can create a file-opening resource:

openFileResource :: FilePath -> IOMode -> Resource Handle openFileResource fp mode = mkResource (openFile fp mode) hClose

Using the Applicative instance, we can then build this up into a Resource for allocating both a file reader and writer:

myHandles :: Resource (Handle, Handle) myHandles = (,) <$> openFileResource "input.txt" ReadMode <*> openFileResource "output.txt" WriteMode

And then we can allocate these Handles with either the bracket pattern:

bracketCopy :: IO () bracketCopy = with myHandles $ \(input, output) -> sourceHandle input $$ sinkHandle output

or using ResourceT itself:

resourcetCopy :: IO () resourcetCopy = runResourceT $ do (releaseKey, (input, output)) <- allocateResource myHandles sourceHandle input $$ sinkHandle output release releaseKey

Hopefully others will find this abstraction useful as well.

Categories: Offsite Blogs

Builder vs Builder

haskell-cafe - Tue, 01/28/2014 - 1:06am
Does anyone know whether blaze-builder is deprecated in favour of bytestring's new Builder module, or are they the same, or... I know Simon is the evil wizard cackling in his dank lair in both cases, and I do remember him saying he was trying to get his work "upstream" into bytestring, but I haven't heard anyone suggesting we should be using Data.ByteString.Lazy.Builder instead of Blaze.ByteString.Builder I can only imagine the integration with the allocation routines is much better now that it's in bytestring, but on the other hand it's hard to upgrade bytestring — it being so low in the stack — so perhaps the original blaze remains the right choice from a bugfix and stability perspective. Thoughts? AfC Sydney _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe< at >haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Categories: Offsite Discussion