Accidentally in Code

I ♥ Haskell

Posted on: October 13, 2009

I knew there was a tighter way to write the derangement code for my assignment, but my Haskell was really rusty and what I had was fast, so I gave up. This morning it came to me – now I have 5 lines instead of 8. I do not have any idea how one would express this in pseudo code, though and it’s probably really quite difficult to read if you’re not familiar with Haskell.

derange1 :: Int -> [[Int]]
derange1 x = perm 0 (makeList x)

makeList :: Int -> [Int]
makeList 0 = []
makeList n = makeList (n-1) ++ [n]

perm :: Int -> [Int] -> [[Int]]            
perm _ [] = [[]]
perm x list = concat [map (e:) (perm (x+1) (delete e list)) |
                                       e <- list, e /= (x+1)]

It’s sometimes surprising how having less can 1) be more work and 2) feel like such an achievement.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Top Posts


Tweet Tweet

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

%d bloggers like this: