0

I want to memoize a function return that a function makes a http request to an API.

I'm unable to do it.

(defn _get_userid 
  [id cid]   
  (p1.nms2/get_uerid id cid))

(def get_userid   
  (memo/ttl _get_userid 
            {} 
            :ttl/threshold p1.constant/ttl-millisecs))
6
  • (p1.nms2/get_uerid id cid) is a function that will call an api Commented Nov 19, 2019 at 16:23
  • 1
    Your usage of the memoize library's ttl function appears correct github.com/clojure/core.memoize/blob/master/src/main/clojure/… could you add the usage, actual output, and expected output to your question? Commented Nov 19, 2019 at 17:23
  • 3
    Please add the require/depency, that brings in memo. Also "I'm unable to do it." is not giving any hints, what is going wrong. Please add a clear statement of the problem you are facing. Commented Nov 19, 2019 at 17:40
  • 1
    i have 2 args to the memoize functions , out of 2 , 1 is actually used and the other is for logging , 1 which is actually used is same where as the one which is not used keeps changing , i need to get both the argument but need to memoize based on only one ? . Commented Nov 20, 2019 at 6:57
  • 2
    In your example both of your arguments are passed to the p1.nms2/get_uerid function, so a memoize there doesn't really make sense if you want different cid's to be cached under the same memoized function. Almost definitely the answer here is to create another function that only takes the parameter you care about and then memoize that. However it would be much more clear if you updated your question with your usage, your expected output, and your actual output Commented Nov 20, 2019 at 7:07

1 Answer 1

1

Given your 2nd parameter is like a context (for logging), you can use a dynamic var so you don't need to pass it as an extra argument to your memoized function.

(def ^:dynamic *cid* nil)

(def get-userid
  (memoize
   (fn [id]
     {:input   id
      :context *cid*
      :output  (inc id)})))

(binding [*cid* "what"]
  (get-userid 1))
;; => {:input 1, :context "what", :output 2}

(binding [*cid* "when"]
  (get-userid 1))
;; => {:input 1, :context "what", :output 2}

(binding [*cid* "why"]
  (get-userid 2))
;; => {:input 2, :context "why", :output 3}

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.