Haskell Convert – For loops

August 20th, 2013 No comments

Loops that transform sequence of data

Let’s start by a neat trick I observed in Fay:

for :: [a] -> (a -> b) -> [b]
for = flip map

or, for the curious:

for :: Functor f => f a -> (a -> b) -> f b
for = flip fmap

Now our good old C++/Java transformation loop

vector<int> out;
for (int x : input) {
  out.push_back(x + 2);
}

can be written in Haskell as

out = for input (\x ->
        x + 2)

or for input (\x -> x + 2) or even for input (+2).

Well, not rocket science, but a bit easier for the imperative eye to read. Using map is still nice when composing functions.

Loops that accumulate data

The old code

int sum = 0;
for (int x : inputs) {
  sum += x;
}

becomes

sum = foldl (+) 0 inputs

Just take care about foldl/foldr laziness, or use a stricter version.

Loops that perform IO

Our old friend

for (int x : inputs) {
  printf("%d", x);
}

becomes

import Control.Monad (forM_)
forM_ inputs putStrLn
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Categories: Uncategorized Tags:

Link Review – late March 2013

March 24th, 2013 No comments

Why this series? When I read something interesting, I mark it with a star, bookmark it, or occasionally retweet it. But then it fades into the void. This series will record my impressions.

Life hacking

Trello is a great free software for creating online task boards. Its applications range from simple TODO lists to complicated process management workflows, however it doesn’t tie the user’s hand. The user is responsible for creating (and occassionally bypassing) the rules. See some interesting Trello usage for project management.

A compact yet to the point summary from Swiss authorities on the electromagnetic fields generated by train lines, with nice figures depicting EM field intensity as the function of distance. Personal suggestion: live at least 50 to 100m away from high voltage or train lines.

Lochart’s Lament is a deeply inspiring writing about teaching maths for kids. Don’t be surprised, the linked resource is just a foreword to the whole thing in PDF.

Games

The Hierarchy of awareness is a nice recollection of basic design practices (mostly AI) that can make computer opponents feel more human-like. I think these practices, if applied, also make human opponents feel more human-like.

Nicolas Cannasse (creator of Haxe language) won a recent LD using his entry Evoland, which was fun to play indeed! Reminds us that indie games should rather be fun and creative, instead of being large-scale. Nevertheless, he left Motion-Twin and is up to new business at Shiro Games, which I guess is worth watching.

Andy Moore posts a shocking post Iteration and Game Design in Mexico. Shocking, since the games he talks about do not require a computer. That is hard to imagine, isn’t it? The post captures a naive, childish (not in the derogatory, but in the pure sense) feeling of having fun in whatever activity. Something that is easy to forget as an adult.

Programming

Gabriel Gonzalez writes about Monad Morphisms in his latest blog post. If you have not yet, read his series from the beginning. He combines understanding of theory and practice in an amazing and entertaining way.

Remember formal languages and model verification from University? Now its’s playtime again! Model Checking Kit provides a load of fun and powerful tools for verifying your models.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Categories: Uncategorized Tags:

Battle Game In Haskell #2 – Fighting using recursion and Either

October 28th, 2012 No comments

Welcome back! Last time we laid the basics of the battle game by applying damage to a unit. However, we had to specify the amount of damage, while it would be more realistic that the damage results from a hit of a hostile unit. Read more…

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Battle Game In Haskell #1 – Intro and basics

October 26th, 2012 No comments

Hi! This is the first in a series of posts in which I gradually refine Haskell code to get a working game. The goal of the series is twofold: First, to motivate myself to put into practice the concepts I read about so far, and second, to serve as a practical example of Haskell.

I don’t plan to explain the various concepts (since others have done already in countless wiki pages and blog posts), but might give pointers on them. If you are not familiar with them, I expect you to google and do the homework.

The game itself is about army battles. Pretty open scope, let’s not fix much upfront and let the game logic unfold as we write it.

Read more…

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Composing functions – functional programming part 1

August 3rd, 2012 No comments

I try to address a relative lack of entry-level material on composing functions targeted for FP newcomers. While the usage and benefit of data types like Option or List are quickly grasped, there is less focus on how to create and compose functions operating in the context of these types. While the following are general for FP, frameworks in focus are functionaljava for Java, and Scalaz for Scala.

Lifting functions to operate in a context

This article is pretty in medias res, holes would be filled in in later parts, but don’t be afraid to comment or google duckduckgo if encountering anything unexplained. A function from a value of type A to a value of type B can be denoted A => B, or in case of functionaljava F[A, B] (please forgive using Scala’s square brackets instead the Java standard less/greater-than sign for type parameters, but it less pain when writing HTML code). Now assume we have a function f1: A => B, and also a value v1: Option[A]. It is evident that since Option is a Functor, we can map f1 on v1 to get a new value v2 of type Option[B]. The code is something like v2: Option[B] = v1.map(f1).

But we hear all the time that FP makes function composition easy. Now if we have a function f0: X => Option[A], can we compose it with our f1 to get a function fc: X => Option[B]? Since the types of the output of f0 and the input of f1 don’t match, a newcomer might begin writing an (anonymous) function taking an optional value and applying map on it with the function (I actually saw this). Instead we can just lift any function to operate in a given Functor context. How? Since Java doesn’t support typeclasses, there are different methods on the F[A, B] class to perform the lifting. To get a function Option[A] => Option[B] from our f1: A => B, we would call f1.mapOption(). There are similiarly named methods for various functors, like mapList, mapSuccess or mapFail (the latter two lifting the function to operate on the success or failure side of a Validation, respectively). So to compose, we would just write fc = f0.andThen(f1.mapOption()) instead of the boilerplate with extra wrapper functions. With Scalaz 6, we can use the polymorphic f1.lift[Option] method for lifting, and for any Functor, not just Option.

Lifting the return type of a function

We might get into a situation where we have a function A => B but would need A => F[B]. If F is Pure (or Pointed, the latter is the new name of Pure in Scalaz 7), then this should be possible (note that if F is a Monad then it is Pure by definintion). Just “should” since again, Java has no typeclass support, so we have to rely on the specific method being available on F[A, B], for example optionK for promoting to F[A, Option[B]]. Just look for methods ending with K, which refers to the Kleisli operation. Indeed, in Scalaz 6 we can use f.kleisli[Option] instead.

Lifting a value

While we are here it is worth mentioning that if F is Pure then we should have a way of producing F[A] from a value of type A. For functionaljava there are various static methods on the data structures, like Option.some, List.list or Validation.success. For Scalaz 6 we can use the a.pure[F] way.

Parting words

Instead of writing a custom wrapper lambda for a specific function, rather lift that function into the context using the appropriate method if there is one. If isn’t (in case of functionaljava) then at least write the lifting method as a general static helper method, or better consider adding it to fj and sending a pull request. In Scala a lambda is more lightweight syntactically than in Java, so in Scala wrapping using a lambda is more common I assume (no hard evidence), but following or at least knowing the FP way can ease our life if eventually refactoring the function to be polymorhic in the Functor type is needed. Have fun coding!

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Categories: Uncategorized Tags: , , , , , ,