So Apparently I Can’t Curry

I was reading “Learn You a Haskell for Great Good”, and this jumped out at me:

People who are not well acquainted with how currying and partial application works often use lambdas where they don’t need to. For instance, the expressions map (+3) [1,6,3,2] and map (\x -> x + 3) [1,6,3,2] are equivalent since both (+3) and (\x -> x + 3) are functions that take a number and add 3 to it. Needless to say, making a lambda in this case is stupid since using partial application is much more readable.

(Check it out here)

I’d heard of currying before (and had it explained to me), but never really got it. In this particular passage, it clicked. I rushed through my previous combinations and permutations stuff, and curried the living daylights out of it.

In particular, code like this:

addPermWithRep(objects, prevPerms)

Could be changed to something like this:

let layer = addPermWithRep(objects) //done somewhere else in the function

And, if layer() was in a closure before, where the only argument it was getting was prevPerms, I could just change it from this: {
  prevPerms in

to this:

AND to top it all off, I realised I had been putting parentheses in where they weren’t needed all the time, like a goddamn numpty: { $0.0 } //wrong{ $0.0 } //right

With sense now smacked into me, I decided to shake it out again, and golfed my permsWithRep function with my newfound tools:

func permsWithRepOfLength
  <T, C: SequenceType where C.Generator.Element == T>(os: C, l: Int) -> [[T]] {
  return reduce(1..<l, map(os, {[$0]})){flatMap($0.0){
    p in map(os){o in p + [o]}}}


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