# News aggregator

### Image Analysis in Haskell

Hey guys! This might be a vague question, but does anyone know any libraries in Haskell for getting data from an image, and storing it in some data structure?

Specifically, I want to see if I can use Haskell to look at a picture of a matrix, and extract the contents and store them so I can perform operations on them. You don't have to do it for me or give me an exact answer, but pointing me in the right direction would be greatly appreciated! Thank you! (If that's too vague, let me know about that too!)

submitted by uncountableB[link] [10 comments]

### How would you implement a trading card game in Haskell?

One of the first projects I tried to tackle in Haskell was the card game "Coop", but I got lost and didn't make much progress. Then I spent some more time learning Haskell, and feel I understand the language much better now, but I'm still not sure how to go from the abstract ideas I've learned to working code.

I want to make a new attempt at a card game. I found this Stackoverflow question that illustrates what I'm thinking of: http://gamedev.stackexchange.com/q/28074 Basically a card game like Magic The Gathering or Hearthstone.

How would you implement a game like this in Haskell?

In an object oriented language I would make a card object that had various methods to respond to different events. These methods could access and modify the game state as needed, in response to events. For example, when a card is played it might receive a "card played" event, and could then perform a special action like giving all other active cards extra health; etc.

I don't know how to approach this problem in Haskell. Although I can do things like implement the State monad myself, I still don't know how to use it. I'm hoping some design guidelines for this problem that has been on my mind will be helpful and interesting.

submitted by Buttons840[link] [20 comments]

### Doing I/O inside of a fold or map operation

If I have a calculation that runs in a "loop", or a fold, is there a way to get the results into the outside world as each iteration happens?

I know I can accumulate the results of each iteration in a Writer or State monad, but that takes memory and my goal is to output them to the outside world without keeping them around in memory.

submitted by asswaxer[link] [20 comments]

### ANN: Saluton Haskell & Nix - A soup to nuts example of deploying Haskell apps on NixOS using NixOps

### returning a polymorphic function

### Noam Lewis: Beware of ‘var’ in for loops, JS programmers

Time and time again, I see people using ‘var’ in the initialization part of a for loop. Example from MDN (Mozilla Developer Network):

for (var i = 0; i < 9; i++) { console.log(i); // more statements }What’s wrong with var i = 0 above? The problem is that **variables declared in a for initialization have function scope**, just like any var declaration does. In other words, they affect the scope of the entire function. Consider the following:

In the inner function, x shadows the outer variable **throughout**, not just inside the for loop. So also the initial statement x = 'inner' at the head of ‘inner’ affects only the locally scoped variable.

This is a classic example of **var hoisting**, which should qualify as one of JavaScript’s awful parts.

**Don’t do it!** Move all your ‘var’ statements to the head of each function, please.

### PhD student or postdoc position announcement

### Mark Jason Dominus: Math.SE report 2015-04

A lot of the stuff I've written in the past couple of years has been on Mathematics StackExchange. Some of it is pretty mundane, but some is interesting. I thought I might have a little meta-discussion in the blog and see how that goes. These are the noteworthy posts I made in April 2015.

Languages and their relation : help is pretty mundane, but interesting for one reason: OP was confused about a statement in a textbook, and provided a reference, which OPs don't always do. The text used the symbol . OP had interpreted it as meaning , but I think what was meant was .

I dug up a copy of the text and groveled over it looking for the explanation of , which is not standard. There was none that I could find. The book even had a section with a glossary of notation, which didn't mention . Math professors can be assholes sometimes.

Is there an operation that takes and , and returns is more interesting. First off, why is this even a reasonable question? Why should there be such an operation? But note that there

*is*an operation that takes and and returns , namely, multiplication, so it's plausible that the operation that OP wants might also exist.But it's easy to see that there is no operation that takes and and returns : just observe that although , the putative operation (call it ) should take and yield , but it should also take and yield . So the operation is not well-defined. And you can take this even further: can be written as , so should also take and yield .

They key point is that the representation of a number, or even an integer, in the form is not unique. (Jargon: "exponentiation is not injective".) You can raise , but having done so you cannot look at the result and know what and were, which is what needs to do.

But if can't do it, how can multiplication do it when it multiplies and and gets ? Does it somehow know what is? No, it turns out that it doesn't need in this case. There is something magical going on there, ultimately related to the fact that if some quantity is increasing by a factor of every units of time, then there is some for which it is exactly doubling every units of time. Because of this there is a marvelous group homomophism $$\log : \langle \Bbb R^+, \times\rangle \to \langle \Bbb R ,+\rangle$$ which can change multiplication into addition

*without*knowing what the base numbers are.In that thread I had a brief argument with someone who thinks that operators apply to expressions rather than to numbers. Well, you can say this, but it makes the question trivial: you can certainly have an "operator" that takes

*expressions*and and yields the*expression*. You just can't expect to apply it to numbers, such as and , because those numbers are not expressions in the form . I remembered the argument going on longer than it did; I originally ended this paragraph with a lament that I wasted more than two comments on this guy, but looking at the record, it seems that I didn't. Good work, Mr. Dominus.how 1/0.5 is equal to 2? wants a simple explanation. Very likely OP is a primary school student. The question reminds me of a similar question, asking why the long division algorithm is the way it is. Each of these is a failure of education to explain what division is actually doing. The long division answer is that long division is an optimization for repeated subtraction; to divide you want to know how many shares of three cookies each you can get from cookies. Long division is simply a notation for keeping track of removing shares, leaving cookies, then further shares, leaving none.

In this question there was a similar answer. is because if you have one cookie, and want to give each kid a share of cookies, you can get out two shares. Simple enough.

I like division examples that involve giving cookies to kids, because cookies are easy to focus on, and because the motivation for equal shares is intuitively understood by everyone who has kids, or who has been one.

There is a general pedagogical principle that an ounce of examples are worth a pound of theory. My answer here is a good example of that. When you explain the theory, you're telling the student how to understand it. When you give an example, though, if it's the right example, the student can't help but understand it, and when they do they'll understand it in their own way, which is better than if you told them how.

How to read a cycle graph? is interesting because hapless OP is asking for an explanation of a particularly strange diagram from Wikipedia. I'm familiar with the eccentric Wikipedian who drew this, and I was glad that I was around to say "The other stuff in this diagram is nonstandard stuff that the somewhat eccentric author made up. Don't worry if it's not clear; this author is notorious for that."

In Expected number of die tosses to get something less than 5, OP calculated as follows: The first die roll is a winner of the time. The second roll is the first winner of the time. The third roll is the first winner of the time. Summing the series we eventually obtain the answer, . The accepted answer does it this way also.

But there's a much easier way to solve this problem. What we really want to know is: how many rolls before we expect to have seen one good one? And the answer is: the expected number of winners per die roll is , expectations are additive, so the expected number of winners per die rolls is , and so we need rolls to expect one winner. Problem solved!

I first discovered this when I was around fifteen, and wrote about it here a few years ago.

As I've mentioned before, this is one of the best things about mathematics: not that it works, but that you can do it by whatever method that occurs to you and you get the same answer. This is where mathematics pedagogy goes wrong most often: it proscribes that you must get the answer by method X, rather than that you must get the answer by hook or by crook. If the student uses method Y, and it works (and if it is correct) that should be worth full credit.

Bad instructors always say "Well, we need to test to see if the student knows method X." No, we should be testing to see if the student can solve problem P. If we are testing for method X, that is a failure of the test or of the curriculum. Because if method X is useful, it is useful because for some problems, it is the only method that works. It is the instructor's job to find one of these problems and put it on the test. If there is no such problem, then X is useless and it is the instructor's job to omit it from the curriculum. If Y always works, but X is faster, it is the instructor's job to explain this, and then to assign a problem for the test where Y would take more time than is available.

I see now I wrote the same thing in 2006. It bears repeating. I also said it again a couple of years ago on math.se itself in reply to a similar comment by Brian Scott:

If the goal is to teach students how to write proofs by induction, the instructor should damned well come up with problems for which induction is the best approach. And if even then a student comes up with a different approach, the instructor should be pleased. ... The directions

**should not begin**[with "prove by induction"]. I consider it a failure on the part of the instructor if he or she has to specify a technique in order to give students practice in applying it.

### Development Environment for Haskell on Windows

After a long process of trial and error, I've finally managed to set up a nice environment for Haskell on Windows.

Here is how I did it in case you are another beginner in trouble.

GHC, Cabal and packagesFirst of all, download and install the Haskell Platform. The current version, 2014.2.0.0, has a bug: cabal init doesn't work.

To fix that, upgrade cabal from version 1.18.x to version 1.20.0.0 with the following commands:

- cd c:\
- cabal update
- cabal install Cabal-1.20.0.0 cabal-install-1.20.0.0

Now you need to delete or rename the executables in C:\Program Files\Haskell Platform\2014.2.0.0\lib\extralibs\bin (your directory might be different) so that the new cabal is visible. This way you don't need to mess with environment variables.

Now you need to install some additional packages:

- cd c:\
- cabal install hlint stylish-haskell ghc-mod

It's very likely that some packages will refuse to install. If the name of the offending package is name, you need to install the package like this:

- cabal unpack name
- cabal install ./name-x.x.x.x

Of course, you must replace name-x.x.x.x with the exact directory created by the first command. Now you can remove the directory:

- rd /s name-x.x.x.x

It goes without saying that after you managed to install the offending package you need to reissue the command cabal install hlint stylish-haskell ghc-mod. Repeat this process as many times as you need.

IDEThis is simple.

Install Intellij IDEA (the community edition will do) and then install the plugin for Haskell authored by JetBrains.

*DO NOT INSTALL HASKFORCE*

The plugin by JetBrains is more complete. For instance you can start a Haskell REPL and send a .hs file to the REPL all without leaving the IDE.

DebuggingGo to File->Settings->Build, Execution, Deployment->Haskell Debugger and choose GHCi as "Prefered (sic) Debugger".

TroubleshootingIf you get a gchi-mod error in IntelliJ, copy ghc.exe from

C:\Program Files\Haskell Platform\2014.2.0.0\binto

%AppData\cabal\binIf you do this, you also need to move cabal.exe from

%AppData\cabal\binto

C:\Program Files\Haskell Platform\2014.2.0.0\lib\extralibs\binIf you copy ghc.exe but don't do this, cabal init and other commands won't work.

Please let me know if you have a cleaner way to set all this up on Windows. My method isn't pretty but it works. submitted by Kiuhnm[link] [28 comments]

### VISSOFT 2015 - Call for Papers: New Ideas or Emerging Results and Tool Demos

### Haskell dev role in Strats at Standard Chartered London

### Summer School on Generic and Effectful Programming (2nd call for participation)

### Data.Hashable instance generation?

### Gabriel Gonzalez: break-1.0.0: A small library for breaking from loops

I've implemented a small library named break for breaking from loops, based off of a previous post of mine.

This library is simple: you wrap the command you want to loop with a function named loop and you call break when you want to exit from the loop.

import Control.Breakimport Control.Monad.State

import Prelude hiding (break)

example :: State Int ()

example = loop (do

n <- lift get -- Inside a `loop`, wrap commands in `lift`

if n < 10

then lift (put (n + 1)) -- You keep looping by default

else break () ) -- Use `break` to exit from the `loop`

The above loop increments n until n is 10 and then exits from the loop. We can verify this by running the State action:

>>> execState example 010

By default, you wrap commands other than break with lift. However, for some effects (like State) you can omit the lift:

example :: State Int ()example = loop (do

n <- get

if n < 10

then put (n + 1)

else break () )

This library uses a Break type which is implemented as ExceptT under the hood:

newtype Break r m a = Break { unBreak :: ExceptT r m a }The break function just "throws an exception":

break :: Monad m => r -> Break r m abreak r = Break (throwE r)

Here "throwing an exception" doesn't use any sort of out-of-band feature built into the Haskell language. "Exceptions" are just ordinary values implemented within the language:

throwE :: Monad m => e -> ExceptT e m athrowE = ExceptT (return (Left e))

... and ExceptT's implementation of (>>=) short-circuits when encountering a Left internally, skipping subsequent commands.

loop is just an ordinary function that repeats the loop body indefinitely and only stops when you break from the loop:

loop :: Monad m => Break r m () -> m rloop m = do

x <- runExceptT (unBreak (forever m))

case x of

Left r -> return r

Right r -> return r

Conceptually we just "catch" the "exceptional value" and return the value. I use quotes because there's no reason to restrict this value to exceptions. You can return any old value from the loop this way:

example :: State Int Boolexample = loop (do

n <- get

if n < 10

then put (n + 1)

else break True )

>>> runState example 0

(True,10)

Notice how I don't have to define a special variation on the forever function that integrates with ExceptT or break to terminate correctly. Instead, break interacts correctly with forever out-of-the-box thanks to Haskell's laziness: forever only lazily evaluates as many actions as necessary and once the internal ExceptT short-circuits the forever function doesn't demand any further command repetitions.

This library also showcases one of Haskell's nifty features: the GeneralizedNewtypeDeriving language extension. Even though I wrap ExceptT in a Break newtype, I can still configure Break to reuse many of the interfaces that were originally implemented for ExceptT, like this:

{-# LANGUAGE GeneralizedNewtypeDeriving #-}newtype Break r m a = Break { unBreak :: ExceptT r m a }

deriving

( Functor

, Applicative

, Monad

, MonadTrans

, MonadIO

, MonadCont

, MonadState s

, MonadWriter w

)

The GeneralizedNewtypeDeriving extension is clever and knows how to wrap and unwrap the newtype to transparently lift all of these type classes to work on Break.

In fact, the library implementation is remarkably small. Here's the entire implementation if you omit the documentation:

{-# LANGUAGE GeneralizedNewtypeDeriving #-}import Control.Applicative (Applicative)

import Control.Monad (forever)

import Control.Monad.IO.Class (MonadIO)

import Control.Monad.Trans.Class (MonadTrans(..))

import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE)

import Control.Monad.Cont (MonadCont )

import Control.Monad.State (MonadState )

import Control.Monad.Writer (MonadWriter)

import Prelude hiding (break)

newtype Break r m a = Break { unBreak :: ExceptT r m a }

deriving

( Functor

, Applicative

, Monad

, MonadTrans

, MonadIO

, MonadCont

, MonadState s

, MonadWriter w

)

break :: Monad m => r -> Break r m a

break r = Break (throwE r)

loop :: Monad m => Break r m () -> m r

loop m = do

x <- runExceptT (unBreak (forever m))

case x of

Left r -> return r

Right r -> return r

Newtypes are probably one of the Haskell features I miss the most when programming in other languages. They are free performance-wise (especially with the recent work on Data.Coerce) and you pay very little code to transport interfaces across newtype boundaries. You get all of the benefits of abstraction and precise types at very little cost.

If you would like to use the break library you can find the library on Hackage or Github.

### Gabriel Gonzalez: optional-args-1.0.0: Optional function arguments

I'm releasing a small library named optional-args to simplify functions that take optional arguments.

Traditionally you would represent an optional argument using Maybe, like this:

greet :: Maybe String -> Stringgreet (Just name) = "Hello, " ++ name

greet Nothing = "Hello"

Then you would provide a specific value by wrapping the value in pure or Just:

>>> greet (pure "John")"Hello, John"

... or you can use the default by suppling empty or Nothing:

>>> greet empty"Hello"

The disadvantage to this approach is that Maybe does not implement the IsString, Num, or Fractional type classes, meaning that you cannot use numeric or string literals in place of Maybe. You have to explicitly wrap them in pure or Just.

The optional-args library provides an Optional type that is equivalent to Maybe, but with additional instances for IsString, Num, and Fractional:

data Optional a = Default | Specific ainstance IsString a => IsString (Optional a)

instance Num a => Num (Optional a)

instance Fractional a => Fractional (Optional a)

Additionally, the constructors are better-named for the task of defining function arguments:

import Data.Optionalgreet :: Optional String -> String

greet (Specific name) = "Hello, " ++ name

greet Default = "Hello"

Since Optional implements IsString, you can use a naked string literal anywhere a function expects an Optional string argument as long as you enable the OverloadedStrings extensions:

>>> :set -XOverloadedStrings>>> greet "John"

"Hello, John"

... and you can still use either Default or empty to use the default:

>>> greet empty"Hello"

Similarly, any function that accepts an Optional numeric argument:

birthday :: Optional Int -> Stringbirthday (Specific age) = "You are " ++ show age ++ " years old!"

birthday Default = "You are one year older!"

... will accept naked numeric literals when you invoke the function:

>>> birthday 20"You are 20 years old!"

For values that are not literals, you can still wrap them in pure:

>>> let age = 20>>> birthday (pure age)

"You are 20 years old!"

The IsString, Num, and Fractional instances are recursive, so you can wrap your types in a more descriptive newtype and derive IsString or Num:

{-# LANGUAGE GeneralizedNewtypeDeriving #-}import Data.Optional

import Data.String (IsString)

newtype Name = Name { getName :: String } deriving (IsString)

greet :: Optional Name -> String

greet (Specific name) = "Hello, " ++ getName name

greet Default = "Hello"

newtype Age = Age { getAge :: Int } deriving (Num)

birthday :: Optional Age -> String

birthday (Specific age) = "You are " ++ show (getAge age) ++ " years old!"

birthday Default = "You are one year older!"

... and you would still be able to use naked numeric or string literals as function arguments:

>>> :set -XOverloadedStrings>>> greet "John"

"Hello, John"

>>> birthday 20

"You are 20 years old!"

The Optional type's Monoid instance also plays nicely with the IsString instance. Specifically, Optional obeys these two laws:

fromString (str1 <> str2) = fromString str1 <> fromString str2fromString mempty = mempty

... which is a fancy way of saying that this code:

>>> greet ("John " <> "Smith")"Hello, John Smith"

... will behave the same as this code:

>>> greet "John Smith""Hello, John Smith"

Even if we were to implement an IsString instance for Maybe, it would not satisfy the second law.

The Optional type is also the only Maybe-like type I know of that has a recursive Monoid instance:

instance Monoid a => Monoid (Optional a)These sorts of recursive instances come in handy when chaining Monoid instances as illustrated in my post on scaling equational reasoning.

The optional-args library also comes with documentation explaining intended usage in detail (almost identical to this post), so if the user clicks on the Optional type they will discover clear instructions on how to use the type.

If you would like to use this, you can find the library on Hackage or Github.