News aggregator

On adding FlexibleContexts to please GHC 7.10

Haskell on Reddit - Sat, 03/21/2015 - 2:20pm

Switching to GHC 7.10 may cause code which was working fine with GHC 7.8 to fail with an error message which suggests to add the FlexibleContexts extension. Adding the extension will indeed cause the error message to disappear, but I would like to argue that this might not be the fix you want.

First of all, nothing bad will happen if you do choose to add FlexibleContexts and call it a day, in the sense that no new regressions will be introduced. That's because the cause of the error message (thanks /u/bgamari!) isn't that some newly-generalized BBP function is now too generic for your code, it's that your code was already implicitly using FlexibleContexts. More precisely, your code has a function which lacks an explicit type signature, and its inferred type requires FlexibleContexts. GHC now requires language extensions for those inferred types as well.

That being said, I believe that a better fix would be to add an explicit type signature to those functions. In the two cases I have encountered so far, the function's inferred type was more polymorphic than what was intended, ghc's error uncovered that small mistake, and adding FlexibleContexts hid the mistake again.

The first case I encountered (thanks /u/adituv!) was a mistake in my own code. I had an [Either ByteString String], and I wanted to find the elements which begin with "module ". Here's a simplified version of the code:

{-# LANGUAGE OverloadedStrings #-} import Data.List import qualified Data.ByteString.Char8 as B type StringLike = Either B.ByteString String findModuleLines :: [StringLike] -> [StringLike] findModuleLines = filter (beginsWithModule) beginsWithModule (Left s) = "module " `B.isPrefixOf` s beginsWithModule (Right s) = "module " `isPrefixOf` s

What's the inferred type of beginsWithModule?

> :t beginsWithModule beginsWithModule :: (Data.String.IsString [a], Eq a) => Either B.ByteString [a] -> Bool

That's much more polymorphic than I need. I could add FlexibleContext to allow the IsString [a] in the inferred type, but I'd rather simply add a type signature to specify that this [a] is simply String:

beginsWithModule :: StringLike -> Bool beginsWithModule (Left s) = "module " `B.isPrefixOf` s beginsWithModule (Right s) = "module " `isPrefixOf` s

The other case I encountered was in the stringsearch package (again thanks to /u/adituv). Here's a simplified version of the problematic code:

import Data.Array.ST import Data.Array.Unboxed replicateAbc :: Int -> UArray Int Char replicateAbc n = runSTUArray $ do ar <- newArray (1, n) 'a' let fillAbc i _ | i > n = return ar fillAbc i 'a' = writeArray ar i 'a' >> fillAbc (i+1) 'b' fillAbc i 'b' = writeArray ar i 'b' >> fillAbc (i+1) 'c' fillAbc i 'c' = writeArray ar i 'c' >> fillAbc (i+1) 'a' fillAbc 1 'a'

We're creating an array of a given length whose contents is "abcabcabc...", using an imperative loop. The resulting type UArray Int Char is an immutable unboxed array, while inside the runSTUArray block, ar has type STUArray s Int Char, indicating that it is not immutable, as it can be modified inside the ST monad.

What is the type of fillAbc? It's an ST computation which returns ar, so its type is clearly intended to be ST s (STUArray s Int Char), but since we didn't specify a type signature, its inferred type is more polymorphic than that.

There are multiple types of mutable arrays, which can be modified in different monads. For this reason, writeArray is polymorphic in m, subject to a constraint MArray a e m. For fillAbc, this constraint becomes:

fillAbc :: MArray (STUArray s) Char m => Int -> Char -> m (STUArray s Int Char)

Just as [a] was more structured than a simple type variable and thus requires FlexibleContext when it appears in a constraint, so does STUArray s. But there is another problem: fillAbc is not polymorphic in s, it only works with the specific, rigid s which was used to create ar. So this time, it is not sufficient to simply give a type signature to fillAbc, it is also necessary to bind s in the outer scope, using the ScopedTypeVariables extension. Since I want to give fillAbc a more specific type which doesn't need a constraint, I don't need FlexibleContexts.

{-# LANGUAGE ScopedTypeVariables #-} import Control.Monad.ST import Data.Array.ST import Data.Array.Unboxed replicateAbc :: Int -> UArray Int Char replicateAbc n = runSTUArray go where go :: forall s. ST s (STUArray s Int Char) go = do ar <- newArray (1, n) 'a' let fillAbc :: Int -> Char -> ST s (STUArray s Int Char) fillAbc i _ | i > n = return ar fillAbc i 'a' = writeArray ar i 'a' >> fillAbc (i+1) 'b' fillAbc i 'b' = writeArray ar i 'b' >> fillAbc (i+1) 'c' fillAbc i 'c' = writeArray ar i 'c' >> fillAbc (i+1) 'a' fillAbc 1 'a'

I have only encountered those two cases, but since many of us are simply accepting GHC's suggestion and adding FlexibleContexts, I wanted to remind you all to take a moment to verify if that's really the fix you want.

submitted by gelisam
[link] [6 comments]
Categories: Incoming News

Wither the Platform

Haskell on Reddit - Sat, 03/21/2015 - 12:23pm
Categories: Incoming News

Need something like convex hull / alpha shapes / voronoi (but not exactly) in haskell.

Haskell on Reddit - Sat, 03/21/2015 - 11:08am

I'm still a bit of a beginner in Haskell. I've been reading the Real World Haskell book a lot lately, and had quite a bit of fun with the Graham Scan / Convex Hull problem.

Now I've encountered a problem at work where this little bit of experience with Haskell could actually be very useful in "the real world", if it weren't for the fact that the challenge at hand is a bit more convoluted

Problem:
I have a list of about 12 million coordinate pairs (2D) in a bunch of files (mostly JSON, but I can easily change that), each with a 3rd "class" property. These points lay in contiguous clouds, which do not necessarily form convex hulls... just shapes. They do not cut each other off, but do have various densities, sizes and shapes.

A good metaphor would be the locations of houses with people who speak a certain language, on a planet where countries do not exist yet, and now we have to decide where to draw the country borders between those groups of people.

Or, in terms of a haskell function: I just need to get a list of polygons (which are lists of 2D vertexes) from this data, so something like a [[(x,y)]] type. Although, It would probably also be useful to preserve the classname of the vertexes for every polygon, so probably more something like [([(x,y)],[Char])].

Or, eventually probably just a JSON file with some logical structure so it's easier to visualize in our applications.

Some starting points:
I first found info on alpha shapes, which forms a convex hull and "eats" away some of the bits using a radius parameter. If a convex hull is like spanning an elastic band/balloon around a bunch of points, then an alpha shape is (kind of) like sucking some of the air out so concavity is possible in large enough areas -- the radius parameter just tells you how thorough it's gonna be.

But alpha shapes could also "eat" holes into the polygons (especially in less dense inner areas), and besides that, it would be preferable if polygons shared borders instead of leaving "demilitarized zones" in between.

Maybe something like a voronoi diagram, except merging adjacent polygons which have an identical class?

I'm not specifically asking for anyone to solve this for me (that's no fun), but any input, pointers or similar cases implemented in Haskell would be awesome.

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

Thiago Negri: Using Facebook's Flux architectural style for game development in Unity 3D

Planet Haskell - Sat, 03/21/2015 - 9:23am
I decided to work again in an old game project. The game is named "Shotem" and the mechanic is quite simple: coins start falling from the sky and you need to "shot them" (got it?). Tap on a coin to shoot it, you gain score if you hit and you lose score if you miss the shot or if a coin falls off the screen (in case you didn't tap it). You have seven bullets to use, each shot (finger tap) consumes a bullet and you need to shake the mobile device to reload your bullets.

The game is still a work in progress, but I added the following video in order to show that it actually works in real life:

<iframe allowfullscreen="allowfullscreen" frameborder="0" height="315" src="https://www.youtube.com/embed/l0qcJUq13Ns" width="420"></iframe>

I'll write the history of the development process of this game. It started in a very naive form, then I converted it to Flux style and left it alone for three months. Now I'm coming back to it and had a pleasant surprise to read the code after forgetting about it. I think Flux style made it easy to continue the project were I left it. This post is 100% opinion based. Please, take a seat.

The first version I coded was very straightforward. Each coin was a GameObject with rendering and game behavior logic. All game state were inside a Singleton and two other objects were responsible for creating coins and handling user taps. Not organized at all.

I was interested in how to code the "reload by shaking" feature. As soon as I got it working, I lost my interest in the game mechanic itself. This happened quite fast actually, Unity 3D has a very nice class to use for dealing with the mobile device gyroscope: Input.gyro.

At the same time, I got in touch with Facebook's Flux architectural style. I tried it in some web projects and had a nice feeling about it. It seemed easier to write, maintain and understand code written in Flux style than the code written in MVC fashion. So, I decided to rewrite the code of Shotem in Flux style.

At first, it didn't seem to fit into Unity's way of doing things. But I worked it out and coded it anyway. It worked fine, then I left the code alone.

Three months later I'm coming back to this project and I didn't remember that I tested Flux style in it. At first I thought: "oh no, I'll need to delete this project and start it over, why did I do it?" Then I did read the code and look at the project structure: I was amazed at how easy it was to get things back on track, I were able to get productive again in less than five minutes! What a pleasant surprise!

Now, I feel that I should share this with the rest of the world. I appreciate feedback, so if you feel that using Flux style in game development is madness or if you feel like giving it a try too, leave a comment.

From now on, I'll use some terms from Flux, e.g. Store, Dispatcher, Action. I won't explain what are their meanings, so feel free to take a little detour and read the official Facebook's Flux website to get a summary of it.

I created a Dispatcher class to register the Stores, dispatch actions, track dependencies between Stores and ensure that the Actions do not cascade. The Dispatcher, in it's full glory, is here:

<script src="https://gist.github.com/thiago-negri/be545cc537bfee832a80.js"></script>

The core game mechanic is encoded in three Stores: CoinStore, handling all coins in the game; GunStore, handling player's ammunition; ScoreStore, tracking user score.

Player input may dispatch two Actions in the game: ShootAction and ReloadGunAction. To handle the physics of the game (falling coins), one Action is sent every FixedUpdate: PhysicsUpdateAction.

The Stores handle each action according to simple rules:

PhysicsUpdateAction is handled by CoinStore by spawning new coins, moving the coins in the screen and removing coins that are off the screen. ScoreStore waits for the CoinStore to finish and then updates the score by decrementing the amount of coins that were removed from CoinStore, because they have fallen off the screen. GunStore ignores this action.

ShootAction is handled by GunStore by decrementing player's ammunition. CoinStore waits for the GunStore and ignores the action if no ammunition was used, otherwise it checks for overlapping coins in the shot area and removes them. ScoreStore waits for GunStore and CoinStore then increases the score by each coin removed or decreases the score in case an ammunition was used and no coin was removed.

ReloadGunAction is handled by GunStore to reset the player's ammunition to seven. CoinStore and ScoreStore ignores this action.

That's the whole game logic. Each Store is observable, the Views register themselves to receive update notifications. When the Store handles an Action that changes its state, it triggers a notification. I've created an abstract class Store to handle this common behavior:

<script src="https://gist.github.com/thiago-negri/90b36ae60138ac332fb7.js"></script>

The listing below is the code of ScoreStore, the other Stores follow the same style:

<script src="https://gist.github.com/thiago-negri/cae3aec33a6deff38b47.js"></script>

Setup code is done in a Singleton GameObject's Awake method, I called it StoreHub because I use this to get the reference to the Stores from other Views:

<script src="https://gist.github.com/thiago-negri/a55cbfcbdff3f9e2721a.js"></script>

ShotemActionGenerator is a helper class to create Actions and send them to Dispatcher, nothing fancy.

The View classes are also simple, for example, the game may play three different sound effects when the GunStore is updated: when a bullet is shot, when user tries to shot without ammunition left and when the gun is reloaded:

<script src="https://gist.github.com/thiago-negri/c9f8d94023286cf6147c.js"></script>

Another view shows the quantity of ammunition remaining, which are just children GameObjects with Renderers that I enable or disable based on the GunStore state:

<script src="https://gist.github.com/thiago-negri/9e8f7311114a8fd633b3.js"></script>

There is a View to show the score, one to show a tip to remind the player to reload the gun when it's empty, another to handle the renderers of each coin visible in the screen, etc. The entire game is made in the same solid base, or may I say "solid flux". Data always flows in a single direction without cascading, there is always an Action that enters the system and triggers something, nothing happens if no Action is dispatched.

I don't know if this design can scale to a big game project, as the style as it is now depends on it running in a single core. But, none of my games are that intense, so I will try to finish this game with Flux. I guess that using Flux will also make it easier to create automated tests of the game mechanic, as it is self-contained. Maybe I'll post some follow up thoughts on it.

Below is an overview image of the current flux of the game. I decided to call "Inception" the layer that generates the Actions, Flux do not give it a name.


Thanks for your time,
Categories: Offsite Blogs

What's the story of this weird type?

haskell-cafe - Fri, 03/20/2015 - 10:21pm
I was reading an answer by Luis Casillas on Stack Overflow http://stackoverflow.com/a/23418746/1477667 and he used a somewhat peculiar type, with apparently not-so-useful constraints: newtype f :-> g = Natural { eta :: forall x. (Functor f, Functor g) => f x -> g x } There are a couple things about it that I don't understand. 1. I can construct a :-> from a function that doesn't satisfy the constraints, and I can pattern match to get access to it, but I can't use it. Why am I allowed to construct it at all? data Mb a = N | J a -- Not a Functor instance
Categories: Offsite Discussion

Mark Jason Dominus: Examples of contracts you should not sign

Planet Haskell - Fri, 03/20/2015 - 6:00pm

Shortly after I posted A public service announcement about contracts Steve Bogart asked me on on Twitter for examples of dealbreaker clauses. Some general types I thought of immediately were:

  • Any nonspecific non-disclosure agreement with a horizon more than three years off, because after three years you are not going to remember what it was that you were not supposed to disclose.

  • Any contract in which you give up your right to sue the other party if they were to cheat you.

  • Most contracts in which you permanently relinquish your right to disparage or publicly criticize the other party.

  • Any contract that leaves you on the hook for the other party's losses if the project is unsuccessful.

  • Any contract that would require you to do something immoral or unethical.

  • Addendum 20150401: Chas. Owens suggests, and I agree, that you not sign a contract that gives the other party ownership of everything you produce, even including things you created on your own time with your own equipment.

A couple of recent specific examples:

  • Comcast is negotiating a contract with our homeowner's association to bring cable Internet to our village; the propsed agreement included a clause in which we promised not to buy Internet service from any other company for the next ten years. I refused to sign. The guy on our side who was negotiating the agreement was annoyed with me. If too many people refuse to sign, maybe Comcast will back out. “Do you think you're going to get FIOS in here in the next ten years?” he asked sarcastically. “No,” I said. “But I might move.”

    Or, you know, I might get sick of Comcast and want to go back to whatever I was using before. Or my satellite TV provider might start delivering satellite Internet. Or the municipal wireless might suddenly improve. Or Google might park a crazy Internet Balloon over my house. Or some company that doesn't exist yet might do something we can't even imagine. Google itself is barely ten years old! The iPhone is only eight!

  • In 2013 I was on a job interview at company X and was asked to sign an NDA that enjoined me from disclosing anything I learned that day for the next ten years. I explained that I could not sign such an agreement because I would not be able to honor it. I insisted on changing it to three years, which is also too long, but I am not completely unwilling to compromise. It's now two years later and I have completely forgotten what we discussed that day; I might be violating the NDA right now for all I know. Had they insisted on ten years, would I have walked out? You bet I would. You don't let your mouth write checks that your ass can't cash.

Categories: Offsite Blogs

Mark Jason Dominus: A public service announcement about contracts

Planet Haskell - Fri, 03/20/2015 - 6:00pm

Every so often, when I am called upon to sign some contract or other, I have a conversation that goes like this:

Me: I can't sign this contract; clause 14(a) gives you the right to chop off my hand.

Them: Oh, the lawyers made us put that in. Don't worry about it; of course we would never exercise that clause.

There is only one response you should make to this line of argument:

Well, my lawyer says I can't agree to that, and since you say that you would never exercise that clause, I'm sure you will have no problem removing it from the contract.

Because if the lawyers made them put in there, that is for a reason. And there is only one possible reason, which is that the lawyers do, in fact, envision that they might one day exercise that clause and chop off your hand.

The other party may proceed further with the same argument: “Look, I have been in this business twenty years, and I swear to you that we have never chopped off anyone's hand.” You must remember the one response, and repeat it:

Great! Since you say that you have never chopped off anyone's hand, then you will have no problem removing that clause from the contract.

You must repeat this over and over until it works. The other party is lazy. They just want the contract signed. They don't want to deal with their lawyers. They may sincerely believe that they would never chop off anyone's hand. They are just looking for the easiest way forward. You must make them understand that there is no easier way forward than to remove the hand-chopping clause.

They will say “The deadline is looming! If we don't get this contract executed soon it will be TOO LATE!” They are trying to blame you for the blown deadline. You should put the blame back where it belongs:

As I've made quite clear, I can't sign this contract with the hand-chopping clause. If you want to get this executed soon, you must strike out that clause before it is TOO LATE.

And if the other party would prefer to walk away from the deal rather than abandon their hand-chopping rights, what does that tell you about the value they put on the hand-chopping clause? They claim that they don't care about it and they have never exercised it, but they would prefer to give up on the whole project, rather than abandon hand-chopping? That is a situation that is well worth walking away from, and you can congratulate yourself on your clean escape.

[ Addendum: Steve Bogart asked on Twitter for examples of unacceptable contract demands; I thought of so many that I put them in a separate article. ]

[ Addendum 20150401: Chas. Owens points out that you don't have to argue about it; you can just cross out the hand-chopping clause, add your initials and date in the margin. I do this also, but then I bring the modification it to the other party's attention, because that is the honest and just thing to do. ]

Categories: Offsite Blogs

Loop School

del.icio.us/haskell - Fri, 03/20/2015 - 5:05pm
Categories: Offsite Blogs

Doctoral Teaching Assistantships in CS at Oxford

General haskell list - Fri, 03/20/2015 - 4:08pm
DOCTORAL TEACHING ASSISTANTSHIPS SOFTWARE ENGINEERING PROGRAMME DEPARTMENT OF COMPUTER SCIENCE, UNIVERSITY OF OXFORD The University of Oxford's Computer Science department is offering two DPhil (PhD) scholarships. The scholarships are for up to five years; they include teaching responsibilities on the department's Software Engineering Programme (SEP), which has been running for over twenty years, offering part-time professional Master's degrees in Software Engineering and in Software & Systems Security. Each scholarship provides a stipend (£14057 pa from October 2015, with small annual increases subsequently) plus full fees. The Department of Computer Science was established in 1957, making it one of the longest established in the country. It is one of the UK's leading computer science departments, ranked first in a number of international rankings. The latest Research Excellence Framework (REF 2014) resulted in the 74 members of the Department having 87% of their research activity ranked 4* ("world-leadi
Categories: Incoming News

Why isn't anyone talking about optimal lambda calculus implementations?

Haskell on Reddit - Fri, 03/20/2015 - 3:39pm

On 1990, John Lamping proposed an optimal algorithm for lambda calculus reduction as per Levy's notion. As far as my understanding goes, it works by translating lambda calculus terms to interaction nets, reducing them, and translating back. Interaction nets are a computational model based on graph rewriting with interesting properties such as computation being local and asynchronous (different from, say, automatas, which are local but synchronized). They are very interesting by themselves, having universal combinators akin to SKI, connections to linear logic, biology, etc. That's not the point, though: what most of this means for functional programming is that John's system is not only optimal on the sense that the minimal amount of duplication is guaranteed (making, i.e., lazy evaluation irrelevant) but is also very promising for the possibility of parallelization exploiting.

Yet, 25 years have passed and there is only one implementation of those ideas on Hackage, which is undocumented and, as far as my source-code-stalking goes, possibly incomplete, since I couldn't find a function to map from nets back to lambdas (it might be there, though).

Anyway, the question holds: why is there almost no interest in implementing those ideas and seeing how well they go in practice?

submitted by SrPeixinho
[link] [22 comments]
Categories: Incoming News

Strongly typed data / API specification librares

haskell-cafe - Fri, 03/20/2015 - 1:06pm
Hi cafe, Does anyone know of any libraries that allow one to describe data / interfaces (think IDLs), with emphasis on good support for modules, strong typing and extensibility? I am thinking in the lines of Thrift[1], Piqi[2], Swagger[3], but with the core data specification language as decoupled as possible from any kind of implementation related things (such as actual representation of data, or RPC / RESTful bindings). haskell-servant[4] and silk-rest[5] are kind of relevant, but they are very much oriented towards RESTful APIs. Sorry if this is slightly off-topic, but I couldn't think anywhere else to inquire about this. Thanks, Ignas [1]: https://thrift.apache.org/ [2]: http://piqi.org/ [3]: http://swagger.io/ [4]: http://haskell-servant.github.io/ [5]: http://silkapp.github.io/rest/
Categories: Offsite Discussion

Lens is unidiomatic Haskell

Haskell on Reddit - Fri, 03/20/2015 - 11:05am
Categories: Incoming News