0

I process all files in a directory, say:

(map file-handler files)

The only parameter to file-handler is naturally a file object. I want to know inside the file-handler the current "index" of the files sequence. The only solution I can see so far is to create a counter in the lexical closure, visible inside file-handler, and increment it there on each step. Perfectly feasible but not quite clojurelike. Is there a pure functional way to manage it?

1
  • 1
    Very often in FP it turns out that you don't need an index even though you thought you did. If you do then as @noisesmith's said, the general principle is to pass the 'mutating' value through the recursion as one of the arguments, e.g. fold and reduce Commented Nov 20, 2014 at 22:05

1 Answer 1

3

map takes 1 or more arguments

(map file-handler (range) files)

there is also a shortcut for this

(map-indexed file-handler files)

This will require updating file-handler to take 2 arguments, or making a wrapper function that takes the index and the file and calls file-handler on the file.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, noisesmith! Neglected the RTFM part, shame on me.
as a general principle, in functional programming you can take any stateful variable, and turn it into an immutable function argument that gets passed forward.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.