News aggregator

Image Analysis in Haskell

Haskell on Reddit - Mon, 06/15/2015 - 10:56pm

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]
Categories: Incoming News

How would you implement a trading card game in Haskell?

Haskell on Reddit - Mon, 06/15/2015 - 10:19pm

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]
Categories: Incoming News

Doing I/O inside of a fold or map operation

Haskell on Reddit - Mon, 06/15/2015 - 9:11pm

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]
Categories: Incoming News

returning a polymorphic function

haskell-cafe - Mon, 06/15/2015 - 3:11pm
Hello list, I'm trying to accomplish something along this line {-# LANGUAGE ScopedTypeVariables #-} f :: IO (a -> a) f = return id main = do (g :: a -> a) <- f print $ g 1 print $ g "ciao" Is it possible or I have to call f more than once to get different g's Thanks paolino _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe< at >haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
Categories: Offsite Discussion

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

Planet Haskell - Mon, 06/15/2015 - 1:50pm

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:

function outer() { var x = 'outer'; function inner() { x = 'inner'; // // ... lots o' code // for (var x = 0; x < 1; x++) { // in for } } inner(); }

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.


Categories: Offsite Blogs

PhD student or postdoc position announcement

haskell-cafe - Mon, 06/15/2015 - 1:45pm
2-year postdoc or 3-year PhD-student position at the University of Innsbruck ============================================================================ The Computational Logic research group at the University of Innsbruck has one open position funded by the FWF (Austrian science fund) via the START project „Certifying Termination and Complexity Proofs of Programs“. The project aims at increasing the reliability in current complexity and termination provers by independently checking the generated proofs. To this end, several analysis techniques will be formalized in the theorem prover Isabelle/HOL, with a focus on term rewriting and Haskell. For this project, we are looking for an enthusiastic young researcher with a background in computational logic. Knowledge of automated termination analysis, complexity analysis, or theorem proving would be an asset. Candidates with a strong theoretical background in related areas are also encouraged to apply. The PhD-student candidate must have a
Categories: Offsite Discussion

Mark Jason Dominus: Math.SE report 2015-04

Planet Haskell - Mon, 06/15/2015 - 1:38pm

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.

Categories: Offsite Blogs

Development Environment for Haskell on Windows

Haskell on Reddit - Mon, 06/15/2015 - 12:58pm

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 packages

First 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:

  1. cd c:\
  2. cabal update
  3. 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:

  1. cd c:\
  2. 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:

  1. cabal unpack name
  2. 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.

IDE

This 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.

Debugging

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

Troubleshooting

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

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

to

%AppData\cabal\bin

If you do this, you also need to move cabal.exe from

%AppData\cabal\bin

to

C:\Program Files\Haskell Platform\2014.2.0.0\lib\extralibs\bin

If 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]
Categories: Incoming News

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

General haskell list - Mon, 06/15/2015 - 11:09am
--------------------------------------- VISSOFT 2015 - Call for Papers: New Ideas or Emerging Results and Tool Demos 3rd IEEE Working Conference on Software Visualization (VISSOFT) September 27-28, 2015, Bremen, Germany Paper submission date: June 29, 2015 Notification: July 31, 2015 http://vissoft.info Software visualization is a broad research area encompassing concepts, methods, tools, and techniques that assist in a range of software engineering and software development activities. Covered aspects include the development and evaluation of approaches for visually analyzing software and software systems, including their structure, execution behavior, and evolution. The VISSOFT IEEE Working Conference on Software Visualization continues the history of the ACM SOFTVIS Symposium on Software Visualization and the IEEE VISSOFT International Workshop on Visualizing Software for Understanding and Analysis. The conference focuses on visualization techniques that target aspects of software maintenance and evol
Categories: Incoming News

Haskell dev role in Strats at Standard Chartered London

General haskell list - Mon, 06/15/2015 - 10:21am
I'm hiring another Haskell dev to join the Strats team in London. Details here: https://donsbot.wordpress.com/2015/06/15/haskell-dev-role-in-strats-at-standard-chartered-london-2/ _______________________________________________ Haskell mailing list Haskell< at >haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell
Categories: Incoming News

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

General haskell list - Mon, 06/15/2015 - 9:12am
Call for Participation SUMMER SCHOOL ON GENERIC AND EFFECTFUL PROGRAMMING St Anne's College, Oxford, 6th to 10th July 2015 http://www.cs.ox.ac.uk/projects/utgp/school/ TOPIC Generic programming is a technique that exploits the inherent structure that exists in data, to automatically produce efficient and flexible algorithms that can be adapted to suit different needs. The goal of this school is to explore datatype-generic programming and related topics from a variety of different angles, emphasizing in particular the interplay of generics and effects. This summer school is the closing activity of the EPSRC-funded project "Unifying Theories of Generic Programming" at Oxford University. LECTURERS Six lecturers from the Programming Languages community, each an acknowledged expert in their specialism, will cover various aspects of generic and effectful programming. Each will give about four hours' lectures, distributed throughout the week. Edwin Brady (Universi
Categories: Incoming News

Data.Hashable instance generation?

haskell-cafe - Mon, 06/15/2015 - 9:05am
Hello, A practical question about getting hashing to work. Having used Data.Map before, I wanted to try Data.HashMap.Lazy instead: ---- {-# LANGUAGE DeriveGeneric #-} import Data.HashMap.Lazy as HM import GHC.Generics (Generic) import Data.Hashable data Colour = Red | Green | Blue deriving Generic instance Hashable Colour foo = HM.insert Red ---- The data and its instance definition are directly from the web page <https://hackage.haskell.org/package/hashable-1.2.1.0/docs/Data-Hashable.html>. However, I det the following error: ---- GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. [1 of 1] Compiling Main ( htest.hs, interpreted ) htest.hs:13:8: No instance for (hashable-1.1.2.5:Data.Hashable.Hashable Colour) arising from a use of `insert' Possible fix: add an instance declaration for (hasha
Categories: Offsite Discussion

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

Planet Haskell - Mon, 06/15/2015 - 8:04am

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.Break
import 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 0
10

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 a
break 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 a
throwE = 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 r
loop 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 Bool
example = 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.

Categories: Offsite Blogs

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

Planet Haskell - Mon, 06/15/2015 - 8:03am

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 -> String
greet (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 a

instance 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.Optional

greet :: 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 -> String
birthday (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 str2

fromString 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.

Categories: Offsite Blogs