I recently ran across CodinGame which is similar to CodeWars but is framed as a series of games you’re writing the logic for instead of textural problems to solve. Needless to say this appeals to me. Happily they support Haskell so I dove in and started in on the tutorial. Blammo! No problem. Onwards to problem #1 in the easy category… two hours later, I finally had a solution that worked. Now if this had been C# it would have been a 5 minute problem tops, but the point of this kind of exercise is precisely that I’m not working in something familiar. I’ve done a few of the katas on CodeWars in Haskell and while somewhat challenging, the easy problems were indeed pretty straightforward. This problem however was much more difficult because it was framed as an imperative problem and that has a much higher impedance mismatch with the normal way of doing things in Haskell. I figured this might be a good example to point out a very different way of approaching what should be a very easy to visualize problem.
So in this scenario, you have Thor who must be guided to the light of power. At the beginning of the program you’re provided with Thor’s starting x/y coordinates as well as the x/y of the light. You write to standard out a direction in the form of N, S, E, W, NW, NE, SE, SW over and over until Thor reaches the destination (or the run times out after 100 moves). So this seems pretty straightforward, you could keep track of your x/y, increment or decrement it as you move and each iteration compare where you are to the target and output the correct direction accordingly. Easy peasy.
I did start out somewhat in this vein, I knew I wasn’t going to be mutating a global variable but my idea was to have a function that took the current x/y and target x/y and did the comparison and outputted the correct direction. This is doable in Haskell just like in C# although you would use recursion instead of a while loop, but otherwise it’s pretty similar. Thinking about this problem for a moment though, I realized you actually know right from the start how many moves in each direction you will need. Using that you could construct the entire list of moves to get to the target and then all that’s left would be to iterate over that list printing out the values one at a time.
Here is the code listing (also in the screenshot at the bottom for reference). The structure of the functions and the all the input!!xyz lines were provided at the start of the problem.
import System.IO import Control.Monad main :: IO () main = do hSetBuffering stdout NoBuffering -- DO NOT REMOVE input_line <- getLine let input = words input_line let lightX = read (input!!0) :: Int -- the X position of the light of power let lightY = read (input!!1) :: Int -- the Y position of the light of power let initialTX = read (input!!2) :: Int -- Thor's starting X position let initialTY = read (input!!3) :: Int -- Thor's starting Y position -- my code starts here let startToTargetX = lightX - initialTX let targetToStartX = initialTX - lightX let startToTargetY = lightY - initialTY let targetToStartY = initialTY - lightY let count = max (max startToTargetY targetToStartY) (max startToTargetX targetToStartX) let vertical = replicate startToTargetY "S" ++ replicate targetToStartY "N" ++ repeat "" let horizontal = replicate startToTargetX "E" ++ replicate targetToStartX "W" ++ repeat "" let pairs = zip vertical horizontal let directions = map (uncurry (++)) (take count pairs) loop directions loop :: [String] -> IO () loop [final] = putStrLn final loop (current:rest) = do putStrLn current loop rest loop  = return ()
Each move is potentially some combination of vertical and horizontal movement and I did not know which direction would contain more moves, so I used Haskell’s lazyness to not have to care. I calculated the total number of moves to get to the target, which is simply the maximum of the horizontal and vertical distances. Then I built up a list of instructions for both directions and appended infinite empty strings to the end. I passed both the horizontal and vertical instruction lists into a zip function that paired them into an infinite list of tuples, and then I took from that list of tuples a number of elements equal to the count I had calculated earlier. Finally for each pair I took the two elements and combined them to build the final string using map. Uncurry for reference, takes a function that normally takes 2 params, and converts it to a function that takes a pair (tuple), that way I can use the standard ++ function with the tuple that got built up by zip.
The main loop function then was just responsible for printing out each value. The first case is matched when there is only one element in the list, which simply outputs that element. The second case is matched when there is at least 2 elements in the list. The final case of
loop  = return ()
is there just to satisfy the compiler that can’t know that we will never call loop with an empty list, however it will never be executed in this solution.
I’m not claiming this is the best way to do things in Haskell, but it seems vastly more idiomatic than copying an imperative style. Hopefully it’s interesting to see how different a solution can be when you’re working with a different toolbox.
I’ve started a new blog series where I attempt to explain functional programming concepts in terms everyday OO programmers will find familiar. Part 1 goes over the overall case for functional programming and part 2 covers some of the ways higher order functions let us create generalized solutions to common problems. Future parts will cover topics like integrating functional programming with existing highly mutable systems and how to do functional programming in your existing language of choice.
There don’t seem to be many NUnit test runners that will monitor your project and automatically re-run your tests whenever your assembly changes on OSX. After some looking around I settled on using the plain nunit.exe that comes with NUnit itself. This requires me to fire off a command line to boot it up each time instead of it just being an app. I figured there had to be a way to get a simple app bundle to wrap the command so that it could be launched like a normal app via spotlight or Alfred or whatever your launcher of choice is.
Enter Platypus, a drop dead simple way to wrap up a shell script, Ruby, Python, Perl, or other “needs to be launched from the command line” utility you might have. Configuration was extremely simple, I created a shell script to kick off NUnit
mono nunit.exe &
Then I told Platypus what script to run and included all of the requisite NUnit files that are needed and hit create.
Make sure to uncheck the “Remain running after initial execution” or the Platypus process will hang around.
If you just want the NUnit app bundle you can get it here.
It’s pretty well established these days that writing User Stories to capture the requirements of your project is “a good thing”. You’d be fairly hard pressed to find a small to mid size group with a giant tome of requirements handed down on high. You’re slightly more likely to see a team getting by with nothing or perhaps a haphazard whiteboard of semi crossed off todo items. Most however, will have some degree of a user story style system. Writing good stories is hard, estimating them is even harder, but the benefits in increased communication and process transparency far outweigh these costs. But what about a situation where there is no communication between developers? What if you are a solo developer and your customer (if you have one that’s not you), isn’t the type who is ever going to engage with an issue tracking system? What benefit then does writing user stories hold over the aforementioned whiteboard, or perhaps a Google doc?
Software development is still software development. Even if you have no need to communicate to another person, you still need to clarify the intent of your work to yourself (and let’s be honest, 2 weeks from now, you are another person and “sound when collected” as a task probably won’t mean jack to you). This is a situation where the format of a user story helps out. Let’s take a look at an example requirement from my primary domain, game development.
Seems simple enough. Now most everyone knows how Super Mario Bros. works and would be able to implement this feature correctly. But what if the developer didn’t know what was supposed to happen? What if they have never played Super Mario Bros.? I would imagine, that an initial implementation might lead to this.
Touching the goomba kills the player, just like the story said. Now you’re probably shaking your head and saying “of course they would know jumping on the goomba kills the goomba and not the player!” and for the implementation of a game that you can look at and play, this is true. We’re generally not interested in reimplementing old games, we are interested in creating our own new ones. If we were creating SMB initially and we wrote out the requirement as a user story, it might look something more like this:
As the player I should be able to see my character die when I touch an enemy.
Some user story advocates would say you really need the “so that…” section on there, which in some cases does seems applicable but in this case “so that the game is challenging” appears fairly redundant to me. I could see a case for “so that I understand what things can kill me” as an addendum as it gets to the reason behind seeing your character pop up and flap his arms and fall but let’s leave it off for this discussion. By phrasing it from the perspective of the player and being specific about when, in this case the “touch an enemy” writing this story has hopefully made clear that there are other ways the player can collide with the enemy, maybe collision from the side is not the same as collision from the top? Again when implementing SMB this isn’t really an issue, but when you’re trying to figure out what the app should do in the first place, this is the kind of thing I find handy to at least bring up to myself. Even if it’s crystal clear ahead of time that yes the enemy should die when Mario arrives from above this at least prompts me to go add that story so I don’t go forgetting bits of functionality.
The second major benefit of user stories to me is that they allow you to take off your project manager hat and put on your heads down programmer hat. When I have filled up my backlog with stories, picked the ones I want to be working on next and plopped them over into the “planned” column I can just grab and go. When that story is done I bump it over to “ready to test” and grab the next one. Sometimes while working on a story a new detail comes up, maybe some additional complexity that wasn’t apparent or that I simply overlooked. In that situation I have to put the old PM hat back on and decide what that does to my prioritization. Thankfully this is usually resolved very quickly and I can get back to development. I find that being able to transition between roles on the project and to be able to focus on one exclusively for periods of time (from a few hours to several days) is very liberating. This part could be accomplished with tasks written any which way you want and any sort of system such as Trello or Jira, but I find the fairly precise wording of a user story to lower the barrier to Getting Things Done more than potentially haphazardly written tasks lists.
So what system do you use? Have you found your own personal development project management nirvana is another set of tools or practices? Please share them in the comments below.
I’ve been doing some beadsprite decorating around the house and have needed some custom designs to load into the app I use for iPad.
Link and Zelda restroom sign
Mario flower, I could only find this as a photo of a made beadsprite not as an image
You wouldn’t think this would be a very complex topic. Something every web server should be pretty good at is letting you see the activity on your server and most importantly the exceptions your app is sure to run into in production. Without that, it’s rather difficult to hunt down your problems. From what I’ve found the typical way this is done is by your frontend, be that Thin or whatever redirecting stdout and stderr to their log files. I find myself in a rather odd situation though, as I am deploying on Windows using Helicon Zoo. No, Linux deployment is probably not an option for this particular situation. Ok, so now Helicon does its thing pretty well, makes your Rack app show up in IIS as an app, etc. Padrino logs its files ok, but exceptions are mysteriously lost to the void. So what I came up with was to redirect $stdout and $stderr to the Padrino logger (at info and warn levels). The idea came from this thread.
In my boot.rb file I add the following
Padrino.after_load do info_wrapper = IOLogWrapper.new(Padrino.logger, :info) warn_wrapper = IOLogWrapper.new(Padrino.logger, :warn) $stdout = info_wrapper $stderr = warn_wrapper end
This wraps up the Padrino standard logger into something that can be assigned to $stdout, namely a subclass of IO. Here’s the IOLogWrapper class
class IOLogWrapper < IO def initialize(logger, level) @logger = logger case level when :info @method_to_call = @logger.method(:info) when :warn @method_to_call = @logger.method(:warn) end end def write(str) @method_to_call.call(str) return str.length end end
Voila! Your exceptions are now logged as info and warning messages in your Padrino log file.
So, I’ve been interviewed by The Examiner. I think this is the first time I’ve been written about… maybe there was something about Monkeybars around the time I spoke at Java One but this is definitely the first “personality piece”.