2

i need to write code like this in clojure.

-- haskell
fns = map (,) [1..3]
head fns $ 1
-- => (1,1)
fns <*> [1..3]
-- => [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]

doesn't work

(def fns (map (partial list) (range 1 3)))
((first fns) 1)
;; => ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn

works, but i think this isn't idiomatic way

(def fns (map (fn [x] `(partial list ~x)) (range 1 3)))
((eval (first fns)) 1)
;; => (1 1)
4
  • Did you look at what the ClassCastException is telling you? Commented Jun 1, 2014 at 21:13
  • Yes. So, I wrote the last code. But, I think that code is ugly. How can I make this better? Commented Jun 1, 2014 at 21:18
  • OK, but rather than punting and using eval, is there any way to make the cast succeed? What about this: stackoverflow.com/q/14559071 Commented Jun 1, 2014 at 21:18
  • How can I take a function from list without evaluating. And is there any way to use that function without eval? Commented Jun 1, 2014 at 21:36

1 Answer 1

6

The function (partial list) is equivalent to just the function list. It's not like haskell where everything is curried - I think you intended partial to see that it's been given only one argument, list, and curry itself up to wait for a second argument. But really that should be (partial partial list): you are attempting to partially apply the function partial itself.

Note also that partially-applied functions are not as common in clojure as they are in haskell, partly because they just don't read so well. Instead of (map (partial partial list) (range 1 3)), if I wanted to build a list of functions like this, I would probably write (for [i (range 1 3)] (fn [j] (list i j))).

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

Comments

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.