Search Results

Search found 74 results on 3 pages for 'defn'.

Page 1/3 | 1 2 3  | Next Page >

  • Getting Vars to bind properly across multiple files

    - by Alex Baranosky
    I am just learning Clojure and am having trouble moving my code into different files. I keep detting this error from the appnrunner.clj - Exception in thread "main" java.lang.Exception: Unable to resolve symbol: -run-application in this context It seems to be finding the namespaces fine, but then not seeing the Vars as being bound... Any idea how to fix this? Here's my code: APPLICATION RUNNER - (ns src/apprunner (:use src/functions)) (def input-files [(resource-path "a.txt") (resource-path "b.txt") (resource-path "c.txt")]) (def output-file (resource-path "output.txt")) (defn run-application [] (sort-files input-files output-file)) (-run-application) APPLICATION FUNCTIONS - (ns src/functions (:use clojure.contrib.duck-streams)) (defn flatten [x] (let [s? #(instance? clojure.lang.Sequential %)] (filter (complement s?) (tree-seq s? seq x)))) (defn resource-path [file] (str "C:/Users/Alex and Paula/Documents/SoftwareProjects/MyClojureApp/resources/" file)) (defn split2 [str delim] (seq (.split str delim))) (defstruct person :first-name :last-name) (defn read-file-content [file] (apply str (interpose "\n" (read-lines file)))) (defn person-from-line [line] (let [sections (split2 line " ")] (struct person (first sections) (second sections)))) (defn formatted-for-display [person] (str (:first-name person) (.toUpperCase " ") (:last-name person))) (defn sort-by-keys [struct-map keys] (sort-by #(vec (map % [keys])) struct-map)) (defn formatted-output [persons output-number] (let [heading (str "Output #" output-number "\n") sorted-persons-for-output (apply str (interpose "\n" (map formatted-for-display (sort-by-keys persons (:first-name :last-name)))))] (str heading sorted-persons-for-output))) (defn read-persons-from [file] (let [lines (read-lines file)] (map person-from-line lines))) (defn write-persons-to [file persons] (dotimes [i 3] (append-spit file (formatted-output persons (+ 1 i))))) (defn sort-files [input-files output-file] (let [persons (flatten (map read-persons-from input-files))] (write-persons-to output-file persons)))

    Read the article

  • Stack overflow in compojure web project

    - by Anders Rune Jensen
    Hi I've been playing around with clojure and have been using it to build a simple little audio player. The strange thing is that sometimes, maybe one out of twenty, when contacting the server I will get the following error: 2010-04-20 15:33:20.963::WARN: Error for /control java.lang.StackOverflowError at clojure.lang.RT.seq(RT.java:440) at clojure.core$seq__4245.invoke(core.clj:105) at clojure.core$filter__5084$fn__5086.invoke(core.clj:1794) at clojure.lang.LazySeq.sval(LazySeq.java:42) at clojure.lang.LazySeq.seq(LazySeq.java:56) at clojure.lang.RT.seq(RT.java:440) at clojure.core$seq__4245.invoke(core.clj:105) at clojure.core$filter__5084$fn__5086.invoke(core.clj:1794) at clojure.lang.LazySeq.sval(LazySeq.java:42) at clojure.lang.LazySeq.seq(LazySeq.java:56) at clojure.lang.RT.seq(RT.java:440) at clojure.core$seq__4245.invoke(core.clj:105) at clojure.core$filter__5084$fn__5086.invoke(core.clj:1794) at clojure.lang.LazySeq.sval(LazySeq.java:42) at clojure.lang.LazySeq.seq(LazySeq.java:56) at clojure.lang.RT.seq(RT.java:440) at clojure.core$seq__4245.invoke(core.clj:105) at clojure.core$filter__5084$fn__5086.invoke(core.clj:1794) at clojure.lang.LazySeq.sval(LazySeq.java:42) at clojure.lang.LazySeq.seq(LazySeq.java:56) at clojure.lang.RT.seq(RT.java:440) ... If I do it right after again it always works. So it appears to be related to timing or something. The code in question is: (defn add-track [t] (common/ref-add tracks t)) (defn add-collection [coll] (doseq [track coll] (add-track track))) and (defn ref-add [ref value] (dosync (ref-set ref (conj @ref value)))) where coll is extracted from this function: (defn tracks-by-album [album] (sort sort-tracks (filter #(= (:album %) album) @tracks))) which uses: (defn get-album-from-track [track] (seq/find-first #(= (:album track) (:name %)) @albums)) (defn sort-tracks [track1 track2] (cond (= (:album track1) (:album track2)) (cond (and (:album-track track1) (:album-track track2)) (< (:album-track track1) (:album-track track2)) :else 0) :else (> (:year (get-album-from-track track1)) (:year (get-album-from-track track2))))) it gets called more or less directly from the request I get in: (when-handle-command cmd params (audio/tracks-by-album decoded-name)) (defn when-handle-command [cmd params data] (println (str "handling command:" cmd)) ....) I never get the handling command in my log, so it must die when it does the tracks-by-album. so it does appear to be the tracks-by-album function from the stack trace. I just don't see why it sometimes works and sometimes doesn't. I say that it's tracks-by-album because it's the only function (including it's children) that does filter, as can be seen in the trace. All the source code is available at: http://code.google.com/p/mucomp/. It's my little hobby project to learn clojure and so far it's quite buggy (this is just one bug :)) so I havn't really liked to tell too many people about it yet :)

    Read the article

  • is this a simple monad example?

    - by zcaudate
    This is my attempt to grok monadic functions after watching http://channel9.msdn.com/Shows/Going+Deep/Brian-Beckman-Dont-fear-the-Monads. h uses bind to compose together two arbitrary functions f and g. What is the unit operator in this case? ;; f :: int - [str] ;; g :: str = [keyword] ;; bind :: [str] - (str - [keyword]) - [keyword] ;; h :: int - [keyword] (defn f [v] (map str (range v))) (defn g [s] (map keyword (repeat 4 s))) (defn bind [l f] (flatten (map f l))) (f 8) ;; = (0 1 2 3 4 5 6 7) (g "s") ;; = (:s :s :s :s) (defn h [v] (bind (f v) g)) (h 9) ;; = (:0 :0 :0 :0 :1 :1 :1 :1 :2 :2 :2 :2 :3 :3 :3 :3 :4 :4 :4 :4 :5 :5 :5 :5)

    Read the article

  • Alternate method to dependent, nested if statements to check multiple states

    - by octopusgrabbus
    Is there an easier way to process multiple true/false states than using nested if statements? I think there is, and it would be to create a sequence of states, and then use a function like when to determine if all states were true, and drop out if not. I am asking the question to make sure there is not a preferred Clojure way to do this. Here is the background of my problem: I have an application that depends on quite a few input files. The application depends on .csv data reports; column headers for each report (.csv files also), so each sequence in the sequence of sequences can be zipped together with its columns for the purposes of creating a smaller sequence; and column files for output data. I use the following functions to find out if a file is present: (defn kind [filename] (let [f (File. filename)] (cond (.isFile f) "file" (.isDirectory f) "directory" (.exists f) "other" :else "(cannot be found)" ))) (defn look-for [filename expected-type] (let [find-status (kind-stat filename expected-type)] find-status)) And here are the first few lines of a multiple if which looks ugly and is hard to maintain: (defn extract-re-values "Plain old-fashioned sub-routine to process real-estate values / 3rd Q re bills extract." [opts] (if (= (utl/look-for (:ifm1 opts) "f") 0) ; got re columns? (if (= (utl/look-for (:ifn1 opts) "f") 0) ; got re data? (if (= (utl/look-for (:ifm3 opts) "f") 0) ; got re values output columns? (if (= (utl/look-for (:ifm4 opts) "f") 0) ; got re_mixed_use_ratio columns? (let [re-in-col-nams (first (utl/fetch-csv-data (:ifm1 opts))) re-in-data (utl/fetch-csv-data (:ifn1 opts)) re-val-cols-out (first (utl/fetch-csv-data (:ifm3 opts))) mu-val-cols-out (first (utl/fetch-csv-data (:ifm4 opts))) chk-results (utl/chk-seq-len re-in-col-nams (first re-in-data) re-rec-count)] I am not looking for a discussion of the best way, but what is in Clojure that facilitates solving a problem like this.

    Read the article

  • StackOverflow in compojure web project

    - by Anders Rune Jensen
    Hi I've been playing around with clojure and have been using it to build a simple little audio player. The strange thing is that sometimes, maybe one out of twenty, when contact the server I will get the following error: 2010-04-20 15:33:20.963::WARN: Error for /control java.lang.StackOverflowError at clojure.lang.RT.seq(RT.java:440) at clojure.core$seq__4245.invoke(core.clj:105) at clojure.core$filter__5084$fn__5086.invoke(core.clj:1794) at clojure.lang.LazySeq.sval(LazySeq.java:42) at clojure.lang.LazySeq.seq(LazySeq.java:56) at clojure.lang.RT.seq(RT.java:440) at clojure.core$seq__4245.invoke(core.clj:105) at clojure.core$filter__5084$fn__5086.invoke(core.clj:1794) at clojure.lang.LazySeq.sval(LazySeq.java:42) at clojure.lang.LazySeq.seq(LazySeq.java:56) at clojure.lang.RT.seq(RT.java:440) at clojure.core$seq__4245.invoke(core.clj:105) at clojure.core$filter__5084$fn__5086.invoke(core.clj:1794) at clojure.lang.LazySeq.sval(LazySeq.java:42) at clojure.lang.LazySeq.seq(LazySeq.java:56) at clojure.lang.RT.seq(RT.java:440) at clojure.core$seq__4245.invoke(core.clj:105) at clojure.core$filter__5084$fn__5086.invoke(core.clj:1794) at clojure.lang.LazySeq.sval(LazySeq.java:42) at clojure.lang.LazySeq.seq(LazySeq.java:56) at clojure.lang.RT.seq(RT.java:440) ... If I do it right after again it always works. So it appears to be related to timing or something. The code in question is: (defn add-track [t] (common/ref-add tracks t)) (defn add-collection [coll] (doseq [track coll] (add-track track))) and (defn ref-add [ref value] (dosync (ref-set ref (conj @ref value)))) where coll is extracted from this function: (defn tracks-by-album [album] (sort sort-tracks (filter #(= (:album %) album) @tracks))) so it does appear to be the tracks-by-album function from the stack trace. I just don't see why it sometimes works and sometimes doesn't.

    Read the article

  • Why does Clojure hang after hacing performed my calculations?

    - by Thomas
    Hi all, I'm experimenting with filtering through elements in parallel. For each element, I need to perform a distance calculation to see if it is close enough to a target point. Never mind that data structures already exist for doing this, I'm just doing initial experiments for now. Anyway, I wanted to run some very basic experiments where I generate random vectors and filter them. Here's my implementation that does all of this (defn pfilter [pred coll] (map second (filter first (pmap (fn [item] [(pred item) item]) coll)))) (defn random-n-vector [n] (take n (repeatedly rand))) (defn distance [u v] (Math/sqrt (reduce + (map #(Math/pow (- %1 %2) 2) u v)))) (defn -main [& args] (let [[n-str vectors-str threshold-str] args n (Integer/parseInt n-str) vectors (Integer/parseInt vectors-str) threshold (Double/parseDouble threshold-str) random-vector (partial random-n-vector n) u (random-vector)] (time (println n vectors (count (pfilter (fn [v] (< (distance u v) threshold)) (take vectors (repeatedly random-vector)))))))) The code executes and returns what I expect, that is the parameter n (length of vectors), vectors (the number of vectors) and the number of vectors that are closer than a threshold to the target vector. What I don't understand is why the programs hangs for an additional minute before terminating. Here is the output of a run which demonstrates the error $ time lein run 10 100000 1.0 [null] 10 100000 12283 [null] "Elapsed time: 3300.856 msecs" real 1m6.336s user 0m7.204s sys 0m1.495s Any comments on how to filter in parallel in general are also more than welcome, as I haven't yet confirmed that pfilter actually works.

    Read the article

  • Parsing data with Clojure, interval problem.

    - by Andrea Di Persio
    Hello! I'm writing a little parser in clojure for learning purpose. basically is a TSV file parser that need to be put in a database, but I added a complication. The complication itself is that in the same file there are more intervals. The file look like this: ###andreadipersio 2010-03-19 16:10:00### USER COMM PID PPID %CPU %MEM TIME root launchd 1 0 0.0 0.0 2:46.97 root DirectoryService 11 1 0.0 0.2 0:34.59 root notifyd 12 1 0.0 0.0 0:20.83 root diskarbitrationd 13 1 0.0 0.0 0:02.84` .... ###andreadipersio 2010-03-19 16:20:00### USER COMM PID PPID %CPU %MEM TIME root launchd 1 0 0.0 0.0 2:46.97 root DirectoryService 11 1 0.0 0.2 0:34.59 root notifyd 12 1 0.0 0.0 0:20.83 root diskarbitrationd 13 1 0.0 0.0 0:02.84 I ended up with this code: (defn is-header? "Return true if a line is header" [line] (> (count (re-find #"^\#{3}" line)) 0)) (defn extract-fields "Return regex matches" [line pattern] (rest (re-find pattern line))) (defn process-lines [lines] (map process-line lines)) (defn process-line [line] (if (is-header? line) (extract-fields line header-pattern)) (extract-fields line data-pattern)) My idea is that in 'process-line' interval need to be merged with data so I have something like this: ('andreadipersio', '2010-03-19', '16:10:00', 'root', 'launchd', 1, 0, 0.0, 0.0, '2:46.97') for every row till the next interval, but I can't figure how to make this happen. I tried with something like this: (def process-line [line] (if is-header? line) (def header-data (extract-fields line header-pattern))) (cons header-data (extract-fields line data-pattern))) But this doesn't work as excepted. Any hints? Thanks!

    Read the article

  • Can I make clojure macro that will allow me to get a list of all functions created by the macro?

    - by Rob Lachlan
    I would like to have a macro which I'll call def-foo. Def-foo will create a function, and then will add this function to a set. So I could call (def-foo bar ...) (def-foo baz ...) And then there would be some set, e.g. all-foos, which I could call: all-foos => #{bar, baz} Essentially, I'm just trying to avoid repeating myself. I could of course define the functions in the normal way, (defn bar ...) and then write the set manually. A better alternative, and simpler than the macro idea, would be to do: (def foos #{(defn bar ...) (defn baz ...)} ) But I'm still curious as to whether there is a good way for the macro idea to work.

    Read the article

  • Clojure: Avoiding stack overflow in Sieve of Erathosthene?

    - by nixx
    Here's my implementation of Sieve of Erathosthene in Clojure (based on SICP lesson on streams): (defn nats-from [n] (iterate inc n)) (defn divide? [p q] (zero? (rem q p))) (defn sieve [stream] (lazy-seq (cons (first stream) (sieve (remove #(divide? (first stream) %) (rest stream)))))) (def primes (sieve (nats-from 2))) Now, it's all OK when i take first 100 primes: (take 100 primes) But, if i try to take first 1000 primes, program breaks because of stack overflow. I'm wondering if is it possible to change somehow function sieve to become tail-recursive and, still, to preserve "streamnes" of algorithm? Any help???

    Read the article

  • Executing a dynamically bound function in Clojure

    - by Carl Smotricz
    I'd like to pre-store a bunch of function calls in a data structure and later evaluate/execute them from within another function. This works as planned for functions defined at namespace level with defn (even though the function definition comes after my creation of the data structure) but will not work with functions defined by let [name (fn or letfn inside the function. Here's my small self-contained example: (def todoA '(funcA)) (def todoB '(funcB)) (def todoC '(funcC)) (def todoD '(funcD)) ; unused (defn funcA [] (println "hello funcA!")) (declare funcB funcC) (defn runit [] (let [funcB (fn [] (println "hello funcB"))] (letfn [(funcC [] (println "hello funcC!"))] (funcA) (eval todoA) ; OK (funcB) ; OK (eval todoB) ; "Unable to resolve symbol: funcB in this context" at line 2 (funcC) ; OK (eval todoC) ; "Unable to resolve symbol: funcC in this context" at line 3 ))) Is there a simple fix I could undertake to get eval'd quoted calls to functions to work for functions defined inside another function?

    Read the article

  • How small is too small (of laptop for a programmer)

    - by defn
    Im thinking of replacing my HP Pavilion dv5-1004nr with Acer Aspire AS5738-6444, I'm a CS student... so im torn between screen size (liking the 15in and decent gpu.. but it weight nearly 8 pounds and battery can barely last 2 hours in power saver mode) and wanting something portable to carry to classes/take notes ect (3 pounds and up to 8 hour battery life of the acer) what would you guys suggest? acer any good? i love my hp keyboard.. (or have links to other good laptops, im aiming for 600$ range?)

    Read the article

  • stop and split generated sequence at repeats - clojure

    - by fitzsnaggle
    I am trying to make a sequence that will only generate values until it finds the following conditions and return the listed results: case head = 0 - return {:origin [all generated except 0] :pattern 0} 1 - return {:origin nil :pattern [all-generated-values] } repeated-value - {:origin [values-before-repeat] :pattern [values-after-repeat] { ; n = int ; x = int ; hist - all generated values ; Keeps the head below x (defn trim-head [head x] (loop [head head] (if (> head x) (recur (- head x)) head))) ; Generates the next head (defn next-head [head x n] (trim-head (* head n) x)) (defn row [x n] (iterate #(next-head % x n) n)) ; Generates a whole row - ; Rows are a max of x - 1. (take (- x 1) (row 11 3)) Examples of cases to stop before reaching end of row: [9 8 4 5 6 7 4] - '4' is repeated so STOP. Return preceding as origin and rest as pattern. {:origin [9 8] :pattern [4 5 6 7]} [4 5 6 1] - found a '1' so STOP, so return everything as pattern {:origin nil :pattern [4 5 6 1]} [3 0] - found a '0' so STOP {:origin [3] :pattern [0]} :else if the sequences reaches a length of x - 1: {:origin [all values generated] :pattern nil} The Problem I have used partition-by with some success to split the groups at the point where a repeated value is found, but would like to do this lazily. Is there some way I can use take-while, or condp, or the :while clause of the for loop to make a condition that partitions when it finds repeats? Some Attempts (take 2 (partition-by #(= 1 %) (row 11 4))) (for [p (partition-by #(stop-match? %) head) (iterate #(next-head % x n) n) :while (or (not= (last p) (or 1 0 n) (nil? (rest p))] {:origin (first p) :pattern (concat (second p) (last p))})) # Updates What I really want to be able to do is find out if a value has repeated and partition the seq without using the index. Is that possible? Something like this - { (defn row [x n] (loop [hist [n] head (gen-next-head (first hist) x n) steps 1] (if (>= (- x 1) steps) (case head 0 {:origin [hist] :pattern [0]} 1 {:origin nil :pattern (conj hist head)} ; Speculative from here on out (let [p (partition-by #(apply distinct? %) (conj hist head))] (if-not (nil? (next p)) ; One partition if no repeats. {:origin (first p) :pattern (concat (second p) (nth 3 p))} (recur (conj hist head) (gen-next-head head x n) (inc steps))))) {:origin hist :pattern nil}))) }

    Read the article

  • Parsing a string, Grammar file.

    - by defn
    How would I separate the below string into its parts. What I need to separate is each < Word including the angle brackets from the rest of the string. So in the below case I would end up with several strings 1. "I have to break up with you because " 2. "< reason " (without the spaces) 3. " . But Let's still " 4. "< disclaimer " 5. " ." I have to break up with you because <reason> . But let's still <disclaimer> . below is what I currently have (its ugly...) boolean complete = false; int begin = 0; int end = 0; while (complete == false) { if (s.charAt(end) == '<'){ stack.add(new Terminal(s.substring(begin, end))); begin = end; } else if (s.charAt(end) == '>') { stack.add(new NonTerminal(s.substring(begin, end))); begin = end; end++; } else if (end == s.length()){ if (isTerminal(getSubstring(s, begin, end))){ stack.add(new Terminal(s.substring(begin, end))); } else { stack.add(new NonTerminal(s.substring(begin, end))); } complete = true; } end++;

    Read the article

  • Java: how to tell if a line in a text file was supposed to be blank?

    - by defn
    I'm working on a project in which I have to read in a Grammar file (breaking it up into my data structure), with the goal of being able to generate a random "DearJohnLetter". My problem is that when reading in the .txt file, I don't know how find out whether the file was supposed to be a completely blank line or not, which is detrimental to the program. Here is an example of part of the file, How do i tell if the next line was supposed to be a blank line? (btw I'm just using a buffered reader) Thanks! <start> I have to break up with you because <reason> . But let's still <disclaimer> . <reason> <dubious-excuse> <dubious-excuse> , and also because <reason> <dubious-excuse> my <person> doesn't like you I'm in love with <another> I haven't told you this before but <harsh> I didn't have the heart to tell you this when we were going out, but <harsh> you never <romantic-with-me> with me any more you don't <romantic> any more my <someone> said you were bad news

    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

  • Difference in F# and Clojure when calling redefined functions

    - by Michiel Borkent
    In F#: > let f x = x + 2;; val f : int -> int > let g x = f x;; val g : int -> int > g 10;; val it : int = 12 > let f x = x + 3;; val f : int -> int > g 10;; val it : int = 12 In Clojure: 1:1 user=> (defn f [x] (+ x 2)) #'user/f 1:2 user=> (defn g [x] (f x)) #'user/g 1:3 user=> (g 10) 12 1:4 user=> (defn f [x] (+ x 3)) #'user/f 1:5 user=> (g 10) 13 Note that in Clojure the most recent version of f gets called in the last line. In F# however still the old version of f is called. Why is this and how does this work?

    Read the article

  • Difference in calling redefined functions in F# and Clojure

    - by Michiel Borkent
    In F#: > let f x = x + 2;; val f : int -> int > let g x = f x;; val g : int -> int > g 10;; val it : int = 12 > let f x = x + 3;; val f : int -> int > g 10;; val it : int = 12 In Clojure: (defn f [x] (+ x 2)) (defn g [x] (f x)) (g 10) ;; => 12 (defn f [x] (+ x 3)) (g 10) ;; => 13 Note that in Clojure the most recent version of f gets called in the last line. In F# however still the old version of f is called. Why is this?

    Read the article

  • How to break out from nested doseqs

    - by fizbin
    Hi, I have a question regarding nested doseq loops. In the start function, once I find an answer I set the atom to true, so that the outer loop validation with :while fails. However it seems that it doesn't break it, and the loops keep on going. What's wrong with it? I am also quite confused with the usage of atoms, refs, agents (Why do they have different names for the update functions when then the mechanism is almost the same?) etc. Is it okay to use an atom in this situation as a flag? Obviously I need a a variable like object to store a state. (def pentagonal-list (map (fn [a] (/ (* a (dec (* 3 a))) 2)) (iterate inc 1))) (def found (atom false)) (defn pentagonal? [a] (let [y (/ (inc (Math/sqrt (inc (* 24 a)))) 6) x (mod (* 10 y) 10)] (if (zero? x) true false))) (defn both-pent? [a b] (let [sum (+ b a) diff (- a b)] (if (and (pentagonal? sum) (pentagonal? diff)) true false))) (defn start [] (doseq [x pentagonal-list :while (false? @found)] (doseq [y pentagonal-list :while (<= y x)] (if (both-pent? x y) (do (reset! found true) (println (- x y)))))))

    Read the article

  • Avoiding symbol capture when using macros to generate functions (or other macros)

    - by Rob Lachlan
    I'm a bit confused as to exactly when symbol capture will occur with clojure macros. Suppose that I have a macro which defines a function from keywords. In this trivial example, (defmacro foo [keywd1 keywd2] `(defn ~(symbol (name keywd1)) [~(symbol (name keywd2))] (* 2 ~(symbol (name keywd2))))) I call (foo :bar :baz), and this gets expanded into (defn bar [baz] (* 2 baz)). So now the question -- can this lead to symbol capture? If so, under what circumstances? I know that it's preferred to use gensym (e.g. bar#) to prevent symbol capture, but in some cases (not many, but still) I'd like to have a pretty macro-expansion, without the auto-generated symbols. Bonus question: does the answer change if we are considering a macro that creates macros?

    Read the article

  • Insertions into Zipper trees on XML files in Clojure

    - by ivar
    I'm confused as how to idiomatically change a xml tree accessed through clojure.contrib's zip-filter.xml. Should be trying to do this at all, or is there a better way? Say that I have some dummy xml file "itemdb.xml" like this: <itemlist> <item id="1"> <name>John</name> <desc>Works near here.</desc> </item> <item id="2"> <name>Sally</name> <desc>Owner of pet store.</desc> </item> </itemlist> And I have some code: (require '[clojure.zip :as zip] '[clojure.contrib.duck-streams :as ds] '[clojure.contrib.lazy-xml :as lxml] '[clojure.contrib.zip-filter.xml :as zf]) (def db (ref (zip/xml-zip (lxml/parse-trim (java.io.File. "itemdb.xml"))))) ;; Test that we can traverse and parse. (doall (map #(print (format "%10s: %s\n" (apply str (zf/xml-> % :name zf/text)) (apply str (zf/xml-> % :desc zf/text)))) (zf/xml-> @db :item))) ;; I assume something like this is needed to make the xml tags (defn create-item [name desc] {:tag :item :attrs {:id "3"} :contents (list {:tag :name :attrs {} :contents (list name)} {:tag :desc :attrs {} :contents (list desc)})}) (def fred-item (create-item "Fred" "Green-haired astrophysicist.")) ;; This disturbs the structure somehow (defn append-item [xmldb item] (zip/insert-right (-> xmldb zip/down zip/rightmost) item)) ;; I want to do something more like this (defn append-item2 [xmldb item] (zip/insert-right (zip/rightmost (zf/xml-> xmldb :item)) item)) (dosync (alter db append-item2 fred-item)) ;; Save this simple xml file with some added stuff. (ds/spit "appended-itemdb.xml" (with-out-str (lxml/emit (zip/root @db) :pad true))) I am unclear about how to use the clojure.zip functions appropriately in this case, and how that interacts with zip-filter. If you spot anything particularly weird in this small example, please point it out.

    Read the article

  • Huge file in Clojure and Java heap space error

    - by trzewiczek
    I posted before on a huge XML file - it's a 287GB XML with Wikipedia dump I want ot put into CSV file (revisions authors and timestamps). I managed to do that till some point. Before I got the StackOverflow Error, but now after solving the first problem I get: java.lang.OutOfMemoryError: Java heap space error. My code (partly taken from Justin Kramer answer) looks like that: (defn process-pages [page] (let [title (article-title page) revisions (filter #(= :revision (:tag %)) (:content page))] (for [revision revisions] (let [user (revision-user revision) time (revision-timestamp revision)] (spit "files/data.csv" (str "\"" time "\";\"" user "\";\"" title "\"\n" ) :append true))))) (defn open-file [file-name] (let [rdr (BufferedReader. (FileReader. file-name))] (->> (:content (data.xml/parse rdr :coalescing false)) (filter #(= :page (:tag %))) (map process-pages)))) I don't show article-title, revision-user and revision-title functions, because they just simply take data from a specific place in the page or revision hash. Anyone could help me with this - I'm really new in Clojure and don't get the problem.

    Read the article

  • Lazy sequence or recur for mathematical power function?

    - by StackedCrooked
    As an exercise I implemented the mathematical power function. Once using recur: (defn power [a n] (let [multiply (fn [x factor i] (if (zero? i) x (recur (* x factor) factor (dec i))))] (multiply a a (dec n)))) And once with lazy-seq: (defn power [a n] (letfn [(multiply [a factor] (lazy-seq (cons a (multiply (* a factor) factor))))] (nth (multiply a a) (dec n)))) Which implementation do you think is superior? I truly have no idea.. (I'd use recur because it's easier to understand.) I read that lazy-seq is fast because is uses internal caching. But I don't see any opportunities for caching in my sample. Am I overlooking something?

    Read the article

  • clojure.algo.monad strange m-plus behaviour with parser-m - why is second m-plus evaluated?

    - by Mark Fisher
    I'm getting unexpected behaviour in some monads I'm writing. I've created a parser-m monad with (def parser-m (state-t maybe-m)) which is pretty much the example given everywhere (here, here and here) I'm using m-plus to act a kind of fall-through query mechanism, in my case, it first reads values from a cache (database), if that returns nil, the next method is to read from "live" (a REST call). However, the second value in the m-plus list is always called, even though its value is disgarded (if the cache hit was good) and the final return is that of the first monadic function. Here's a cutdown version of the issue i'm seeing, and some solutions I found, but I don't know why. My questions are: Is this expected behaviour or a bug in m-plus? i.e. will the 2nd method in a m-plus list always be evaluated if the first item returns a value? Minor in comparison to the above, but if i remove the call _ (fetch-state) from checker, when i evaluate that method, it prints out the messages for the functions the m-plus is calling (when i don't think it should). Is this also a bug? Here's a cut-down version of the code in question highlighting the problem. It simply checks key/value pairs passed in are same as the initial state values, and updates the state to mark what it actually ran. (ns monods.monad-test (:require [clojure.algo.monads :refer :all])) (def parser-m (state-t maybe-m)) (defn check-k-v [k v] (println "calling with k,v:" k v) (domonad parser-m [kv (fetch-val k) _ (do (println "k v kv (= kv v)" k v kv (= kv v)) (m-result 0)) :when (= kv v) _ (do (println "passed") (m-result 0)) _ (update-val :ran #(conj % (str "[" k " = " v "]"))) ] [k v])) (defn filler [] (println "filler called") (domonad parser-m [_ (fetch-state) _ (do (println "filling") (m-result 0)) :when nil] nil)) (def checker (domonad parser-m [_ (fetch-state) result (m-plus ;; (filler) ;; intitially commented out deliberately (check-k-v :a 1) (check-k-v :b 2) (check-k-v :c 3))] result)) (checker {:a 1 :b 2 :c 3 :ran []}) When I run this as is, the output is: > (checker {:a 1 :b 2 :c 3 :ran []}) calling with k,v: :a 1 calling with k,v: :b 2 calling with k,v: :c 3 k v kv (= kv v) :a 1 1 true passed k v kv (= kv v) :b 2 2 true passed [[:a 1] {:a 1, :b 2, :c 3, :ran ["[:a = 1]"]}] I don't expect the line k v kv (= kv v) :b 2 2 true to show at all. The first function to m-plus (as seen in the final output) is what is returned from it. Now, I've found if I pass a filler into m-plus that does nothing (i.e. uncomment the (filler) line) then the output is correct, the :b value isn't evaluated. If I don't have the filler method, and make the first method test fail (i.e. change it to (check-k-v :a 2) then again everything is good, I don't get a call to check :c, only a and b are tested. From my understanding of what the state-t maybe-m transformation is giving me, then the m-plus function should look like: (defn m-plus [left right] (fn [state] (if-let [result (left state)] result (right state)))) which would mean that right isn't called unless left returns nil/false. I'd be interested to know if my understanding is correct or not, and why I have to put the filler method in to stop the extra evaluation (whose effects I don't want to happen). Apologies for the long winded post!

    Read the article

1 2 3  | Next Page >