Search Results

Search found 7019 results on 281 pages for 'learning clojure'.

Page 8/281 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Whats the point of lazy-seq in clojure?

    - by dbyrne
    I am looking through some example Fibonacci sequence clojure code: (def fibs (lazy-cat [1 2] (map + fibs (rest fibs)))) I generally understand what is going on, but don't quite understand the point of lazy-cat. I know that lazy-cat is a macro that is translating to something like this: (def fibs (concat (lazy-seq [1 2]) (lazy-seq (map + fibs (rest fibs))))) What exactly is lazy-seq accomplishing? It would still be evaluated lazily even without lazy-seq? Is this strictly for caching purposes?

    Read the article

  • Clojure program reading its own MANIFEST.MF

    - by Ralph
    How can a Clojure program find its own MANIFEST.MF (assuming it is packaged in a JAR file). I am trying to do this from my "-main" function, but I can't find a class to use in the following code: (.getValue (.. (java.util.jar.Manifest. (.openStream (java.net.URL. (str "jar:" (.. (class **WHAT-GOES-HERE**) getProtectionDomain getCodeSource getLocation) "!/META-INF/MANIFEST.MF")))) getMainAttributes) "Build-number")) Thanks.

    Read the article

  • When should clojure keywords be in namespaces?

    - by Rob
    In clojure, keywords evaluate to themselves, e.g.: >>:test :test They don't take any parameters, and they aren't bound to anything. Why then, would we need to qualify keywords in a namespace? I know that creating isa hierachies using derive requires namespace qualified keywords. Are there any other cases where there is a clear need for keywords to be in a namespace?

    Read the article

  • Project Euler #9 (Pythagorean triplets) in Clojure

    - by dbyrne
    My answer to this problem feels too much like these solutions in C. Does anyone have any advice to make this more lispy? (use 'clojure.test) (:import 'java.lang.Math) (with-test (defn find-triplet-product ([target] (find-triplet-product 1 1 target)) ([a b target] (let [c (Math/sqrt (+ (* a a) (* b b)))] (let [sum (+ a b c)] (cond (> a target) "ERROR" (= sum target) (reduce * (list a b (int c))) (> sum target) (recur (inc a) 1 target) (< sum target) (recur a (inc b) target)))))) (is (= (find-triplet-product 1000) 31875000)))

    Read the article

  • Strange behaviour of keywords within macros in Clojure

    - by mikera
    I'm a little confused by how keyword accesses seem to behave in Clojure when they are evaluated at macro expansion time. The following works as I expect: (def m {:a 1}) (:a m) => 1 However the same keyword access doesn't seem to work within a macro: (def m {:a 1}) (defmacro get-a [x] (:a x)) (get-a m) => nil Any idea what is going on here?

    Read the article

  • Type hinting for functions in Clojure

    - by mikera
    I'm trying to resolve a reflection warning in Clojure that seems to result from the lack of type inference on function return values that are normal Java objects. Trivial example code that demonstrates the issue: (set! *warn-on-reflection* true) (defn foo [#^Integer x] (+ 3 x)) (.equals (foo 2) (foo 2)) => Reflection warning, NO_SOURCE_PATH:10 - call to equals can't be resolved. true What is the best way to solve this? Can this be done with type hints?

    Read the article

  • Can't import clojure records

    - by Zubair
    I have created a record like this: (defrecord User [user-id email]) :but when I try to access it from another name-space I get the error: (User. "name" "email") java.lang.IllegalArgumentException: Unable to resolve classname: User It works when I do: (oe.model.modelcore.User. "name" "email") : I know I will need to import the Java class, but is there any way for clojure to do this automatically when I do: (use 'oe.model.modelcore :reload)

    Read the article

  • Writing and Understanding code

    - by Kitex
    I can write code. I can read code but I can't implement good code. How to develop deep understanding of any framework or stuff that we are working on? Is it looking into documentation and working on it? I have seen in this form that people that have great understanding of things they are working on. How is this possible? How to not scrape on the surface only? How to manage time vs learning vs productivity?

    Read the article

  • (partial apply str) and apply-str in clojure's ->

    - by Jason Baker
    If I do the following: user=> (-> ["1" "2"] (partial apply str)) #<core$partial__5034$fn__5040 clojure.core$partial__5034$fn__5040@d4dd758> ...I get a partial function back. However, if I bind it to a variable: user=> (def apply-str (partial apply str)) #'user/apply-str user=> (-> ["1" "2" "3"] apply-str) "123" ...the code works as I intended it. I would assume that they are the same thing, but apparently that isn't the case. Can someone explain why this is to me?

    Read the article

  • Iterator blocks in Clojure?

    - by Checkers
    I am using clojure.contrib.sql to fetch some records from an SQLite database. (defn read-all-foo [] (with-connection *db* (with-query-results res ["select * from foo"] (into [] res)))) Now, I don't really want to realize the whole sequence before returning from the function (i.e. I want to keep it lazy), but if I return res directly or wrap it some kind of lazy wrapper (for example I want to make a certain map transformation on result sequence), SQL-related bindings will be reset and connection will be closed after I return, so realizing the sequence will throw an exception. How can I enclose the whole function in a closure and return a kind of iterator block (like yield in C# or Python)? Or is there another way to return a lazy sequence from this function?

    Read the article

  • How to return the output of a recursive function in Clojure

    - by Silanglaya Valerio
    Hi everyone! I'm new to functional languages and clojure, so please bear with me... I'm trying to construct a list of functions, with either random parameters or constants. The function that constructs the list of functions is already working, though it doesn't return the function itself. I verified this using println. Here is the snippet: (def operations (list #(- %1 %2) #(+ %1 %2) #(* %1 %2) #(/ %1 %2))) (def parameters (list \u \v \w \x \y \z)) (def parameterlistcount 6) (def paramcount 2) (def opcount 4) (defn generateFunction "Generates a random function list" ([] (generateFunction 2 4 0.5 0.6 '())) ([pc maxdepth fp pp function] (if (and (> maxdepth 0) (< (rand) fp)) (dotimes [i 2] (println(conj (generateFunction pc (dec maxdepth) fp pp function) {:op (nth operations (rand-int opcount))}))) (if (and (< (rand) pp) (> pc 0)) (do (dec pc) (conj function {:param (nth parameters (rand-int parameterlistcount))})) (conj function {:const (rand-int 100)}))))) Any help will be appreciated, thanks!

    Read the article

  • Clojure: Equivalent to Common Lisp READ function?

    - by jkndrkn
    Hi there. When I want to read in an S-expression stored in a file into a running Common Lisp program, I do the following: (defun load-file (filename) "Loads data corresponding to a s-expression in file with name FILENAME." (with-open-file (stream filename) (read stream))) If, for example, I have a file named foo.txt that contains the S-expression (1 2 3), the above function will return that S-expression if called as follows: (load-file "foo.txt"). I've been searching and searching and have not found an equally elegant solution in Clojure. Any ideas? Thanks!

    Read the article

  • Overriding equals, hashCode and toString in a Clojure deftype

    - by mikera
    I'm trying to create a new type in Clojure using deftype to implement a two dimensional (x,y) coordinate, which implements a "Location" protocol. I'd also like to have this implement the standard Java equals, hashCode and toString methods. My initial attempt is: (defprotocol Location (get-x [p]) (get-y [p]) (add [p q])) (deftype Point [#^Integer x #^Integer y] Location (get-x [p] x) (get-y [p] y) (add [p q] (let [x2 (get-x q) y2 (get-y q)] (Point. (+ x x2) (+ y y2)))) Object (toString [self] (str "(" x "," y ")")) (hashCode [self] (unchecked-add x (Integer/rotateRight y 16))) (equals [self b] (and (XXXinstanceofXXX Location b) (= x (get-x b)) (= y (get-y b))))) However the equals method still needs some way of working out if the b parameter implements the Location protocol. What is the right approach? Am I on the right track?

    Read the article

  • Clojure lots of threads

    - by Timothy Baldridge
    I just got done watching Rick Hickey's "Clojure Concurrency" talk, and I have a few questions about threads. Let's say I have a situation with lots of Agents, let's say 10,000 of them running one machine. I'd rather not have 10,000 CPU threads running at once, but I don't want threads to be blocked by the actions of other threads. In this example I won't really be waiting for replies, instead each Agent will be sending a message or two, and then waiting until it gets a message. How would I structure a program like this without getting 10k OS threads which would probably end up slowing the system down.

    Read the article

  • Clojure - tail recursive sieve of Eratosthenes

    - by Konrad Garus
    I have this implementation of the sieve of Eratosthenes in Clojure: (defn sieve [n] (loop [last-tried 2 sift (range 2 (inc n))] (if (or (nil? last-tried) (> last-tried n)) sift (let [filtered (filter #(or (= % last-tried) (< 0 (rem % last-tried))) sift)] (let [next-to-try (first (filter #(> % last-tried) filtered))] (recur next-to-try filtered)))))) For larger n (like 20000) it ends with stack overflow. Why doesn't tail call elimination work here? How to fix it?

    Read the article

  • Chain call in clojure?

    - by Konrad Garus
    I'm trying to implement sieve of Eratosthenes in Clojure. One approach I would like to test is this: Get range (2 3 4 5 6 ... N) For 2 <= i <= N Pass my range through filter that removes multiplies of i For i+1th iteration, use result of the previous filtering I know I could do it with loop/recur, but this is causing stack overflow errors (for some reason tail call optimization is not applied). How can I do it iteratively? I mean invoking N calls to the same routine, passing result of ith iteration to i+1th.

    Read the article

  • Clojure / HBase: How to Import HBaseTestingUtility in v0.94.6.1

    - by David Williams
    In Clojure, if I want to start a test cluster using the hbase testing utility, I have to annotate my dependencies with: [org.apache.hbase/hbase "0.92.2" :classifier "tests" :scope "test"] First of all, I have no idea what this means. According to leiningens sample project.clj ;; Dependencies are listed as [group-id/name version]; in addition ;; to keywords supported by Pomegranate, you can use :native-prefix ;; to specify a prefix. This prefix is used to extract natives in ;; jars that don't adhere to the default "<os>/<arch>/" layout that ;; Leiningen expects. Question 1: What does that mean? Question 2: If I upgrade the version: [org.apache.hbase/hbase "0.94.6.1" :classifier "tests" :scope "test"] Then I receive a ClassNotFoundException Exception in thread "main" java.lang.ClassNotFoundException: org.apache.hadoop.hbase.HBaseConfiguration Whats going on here and how do I fix it?

    Read the article

  • Dynamic scoping in Clojure?

    - by j-g-faustus
    Hi, I'm looking for an idiomatic way to get dynamically scoped variables in Clojure (or a similar effect) for use in templates and such. Here is an example problem using a lookup table to translate tag attributes from some non-HTML format to HTML, where the table needs access to a set of variables supplied from elsewhere: (def *attr-table* ; Key: [attr-key tag-name] or [boolean-function] ; Value: [attr-key attr-value] (empty array to ignore) ; Context: Variables "tagname", "akey", "aval" '( ; translate :LINK attribute in <a> to :href [:LINK "a"] [:href aval] ; translate :LINK attribute in <img> to :src [:LINK "img"] [:src aval] ; throw exception if :LINK attribute in any other tag [:LINK] (throw (RuntimeException. (str "No match for " tagname))) ; ... more rules ; ignore string keys, used for internal bookkeeping [(string? akey)] [] )) ; ignore I want to be able to evaluate the rules (left hand side) as well as the result (right hand side), and need some way to put the variables in scope at the location where the table is evaluated. I also want to keep the lookup and evaluation logic independent of any particular table or set of variables. I suppose there are similar issues involved in templates (for example for dynamic HTML), where you don't want to rewrite the template processing logic every time someone puts a new variable in a template. Here is one approach using global variables and bindings. I have included some logic for the table lookup: ;; Generic code, works with any table on the same format. (defn rule-match? [rule-val test-val] "true if a single rule matches a single argument value" (cond (not (coll? rule-val)) (= rule-val test-val) ; plain value (list? rule-val) (eval rule-val) ; function call :else false )) (defn rule-lookup [test-val rule-table] "looks up rule match for test-val. Returns result or nil." (loop [rules (partition 2 rule-table)] (when-not (empty? rules) (let [[select result] (first rules)] (if (every? #(boolean %) (map rule-match? select test-val)) (eval result) ; evaluate and return result (recur (rest rules)) ))))) ;; Code specific to *attr-table* (def tagname) ; need these globals for the binding in html-attr (def akey) (def aval) (defn html-attr [tagname h-attr] "converts to html attributes" (apply hash-map (flatten (map (fn [[k v :as kv]] (binding [tagname tagname akey k aval v] (or (rule-lookup [k tagname] *attr-table*) kv))) h-attr )))) (defn test-attr [] "test conversion" (prn "a" (html-attr "a" {:LINK "www.google.com" "internal" 42 :title "A link" })) (prn "img" (html-attr "img" {:LINK "logo.png" }))) user=> (test-attr) "a" {:href "www.google.com", :title "A link"} "img" {:src "logo.png"} This is nice in that the lookup logic is independent of the table, so it can be reused with other tables and different variables. (Plus of course that the general table approach is about a quarter of the size of the code I had when I did the translations "by hand" in a giant cond.) It is not so nice in that I need to declare every variable as a global for the binding to work. Here is another approach using a "semi-macro", a function with a syntax-quoted return value, that doesn't need globals: (defn attr-table [tagname akey aval] `( [:LINK "a"] [:href ~aval] [:LINK "img"] [:src ~aval] [:LINK] (throw (RuntimeException. (str "No match for " tagname))) ; ... more rules [(string? ~akey)] [] ))) Only a couple of changes are needed to the rest of the code: In rule-match?, when syntax-quoted the function call is no longer a list: - (list? rule-val) (eval rule-val) + (seq? rule-val) (eval rule-val) In html-attr: - (binding [tagname tagname akey k aval v] - (or (rule-lookup [k tagname] *attr-table*) kv))) + (or (rule-lookup [k tagname] (attr-table tagname k v)) kv))) And we get the same result without globals. (And without dynamic scoping.) Are there other alternatives to pass along sets of variable bindings declared elsewhere, without the globals required by Clojure's binding? Is there an idiomatic way of doing it, like Ruby's binding or Javascript's function.apply(context)?

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >