Reply to post: Rule 3: Functions should be curried.

Learn you Func Prog on five minute quick!

the spectacularly refined chap

Rule 3: Functions should be curried.

Rationale: This makes it easier to reason about the code.

I've never seen that used as a justification, curried and tuple forms are essentially equivalent in terms of analysis, indeed it's easy enough to convert between them. Rather curried functions are one of the bits of scaffolding at the heart of true functional programming, i.e. functions as first class objects. Partial application of curried functions is one of the key methods of advancing code re-use by making a general function specific in a given context.

e.g. to add four to each of a list of numbers on SML:

fun curry f a b = f(a,b)

val input = [3, 6, 9, 12, 15]

val input_plus_4 = map (curry (op +) 4) input;

For the uninitiated:

"op +" converts the built in + operator into tuple form, i.e. a + b becomes +(a,b).

curry (op +) uses the curry function we supply to convert that into curried form: + a b.

(curry (op +) 4) creates a function which supplies an implied first parameter: + 4 b.

map (curry (op +) 4) supplies that new function as a parameter to the map function, which returns a function which applies it to each item in a list.

map (curry (op +) 4) input then applies that final function to the input and returns a new list.

I wouldn't have said that's any easier to analyse, but it certainly allows for complex ideas to be expressed quickly and succinctly.

POST COMMENT House rules

Not a member of The Register? Create a new account here.

  • Enter your comment

  • Add an icon

Anonymous cowards cannot choose their icon

Biting the hand that feeds IT © 1998–2019