Search Results

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

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

  • Mutation Problem - Clojure

    - by Silanglaya Valerio
    having trouble changing an element of my function represented as a list. code for random function: (defn makerandomtree-10 [pc maxdepth maxwidth fpx ppx] (if-let [output (if (and (< (rand) fpx) (> maxdepth 0)) (let [head (nth operations (rand-int (count operations))) children (doall (loop[function (list) width maxwidth] (if (pos? width) (recur (concat function (list (makerandomtree-10 pc (dec maxdepth) (+ 2 (rand-int (- maxwidth 1))) fpx ppx))) (dec width)) function)))] (concat (list head) children)) (if (and (< (rand) ppx) (>= pc 0)) (nth parameters (rand-int (count parameters))) (rand-int 100)))] output )) I will provide also a mutation function, which is still not good enough. I need to be able to eval my statement, so the following is still insufficient. (defn mutate-5 "chooses a node changes that" [function pc maxwidth pchange] (if (< (rand) pchange) (let [output (makerandomtree-10 pc 3 maxwidth 0.5 0.6)] (if (seq? output) output (list output))) ;mutate the children of root ;declare an empty accumulator list, with root as its head (let [head (list (first function)) children (loop [acc(list) walker (next function)] (println "----------") (println walker) (println "-----ACC-----") (println acc) (if (not walker) acc (if (or (seq? (first function)) (contains? (set operations) (first function))) (recur (concat acc (mutate-5 walker pc maxwidth pchange)) (next walker)) (if (< (rand) pchange) (if (some (set parameters) walker) (recur (concat acc (list (nth parameters (rand-int (count parameters))))) (if (seq? walker) (next walker) nil)) (recur (concat acc (list (rand-int 100))) (if (seq? walker) (next walker) nil))) (recur acc (if (seq? walker) (next walker) nil)))) ))] (concat head (list children))))) (side note: do you have any links/books for learning clojure?)

    Read the article

  • Clojure agents consuming from a queue

    - by erikcw
    I'm trying to figure out the best way to use agents to consume items from a Message Queue (Amazon SQS). Right now I have a function (process-queue-item) that grabs an items from the queue, and processes it. I want to process these items concurrently, but I can't wrap my head around how to control the agents. Basically I want to keep all of the agents busy as much as possible without pulling to many items from the Queue and developing a backlog (I'll have this running on a couple of machines, so items need to be left in the queue until they are really needed). Can anyone give me some pointers on improving my implementation? (def active-agents (ref 0)) (defn process-queue-item [_] (dosync (alter active-agents inc)) ;retrieve item from Message Queue (Amazon SQS) and process (dosync (alter active-agents dec))) (defn -main [] (def agents (for [x (range 20)] (agent x))) (loop [loop-count 0] (if (< @active-agents 20) (doseq [agent agents] (if (agent-errors agent) (clear-agent-errors agent)) ;should skip this agent until later if it is still busy processing (not sure how) (send-off agent process-queue-item))) ;(apply await-for (* 10 1000) agents) (Thread/sleep 10000) (logging/info (str "ACTIVE AGENTS " @active-agents)) (if (> 10 loop-count) (do (logging/info (str "done, let's cleanup " count)) (doseq [agent agents] (if (agent-errors agent) (clear-agent-errors agent))) (apply await agents) (shutdown-agents)) (recur (inc count)))))

    Read the article

  • Create a HTML table from nested maps (and vectors)

    - by Kenny164
    I'm trying to create a table (a work schedule) I have coded previously using python, I think it would be a nice introduction to the Clojure language for me. I have very little experience in Clojure (or lisp in that matter) and I've done my rounds in google and a good bit of trial and error but can't seem to get my head around this style of coding. Here is my sample data (will be coming from an sqlite database in the future): (def smpl2 (ref {"Salaried" [{"John Doe" ["12:00-20:00" nil nil nil "11:00-19:00"]} {"Mary Jane" [nil "12:00-20:00" nil nil nil "11:00-19:00"]}] "Shift Manager" [{"Peter Simpson" ["12:00-20:00" nil nil nil "11:00-19:00"]} {"Joe Jones" [nil "12:00-20:00" nil nil nil "11:00-19:00"]}] "Other" [{"Super Man" ["07:00-16:00" "07:00-16:00" "07:00-16:00" "07:00-16:00" "07:00-16:00"]}]})) I was trying to step through this originally using for then moving onto doseq and finally domap (which seems more successful) and dumping the contents into a html table (my original python program outputed this from a sqlite database into an excel spreadsheet using COM). Here is my attempt (the create-table fn): (defn html-doc [title & body] (html (doctype "xhtml/transitional") [:html [:head [:title title]] [:body body]])) (defn create-table [] [:h1 "Schedule"] [:hr] [:table (:style "border: 0; width: 90%") [:th "Name"][:th "Mon"][:th "Tue"][:th "Wed"] [:th "Thur"][:th "Fri"][:th "Sat"][:th "Sun"] [:tr (domap [ct @smpl2] [:tr [:td (key ct)] (domap [cl (val ct)] (domap [c cl] [:tr [:td (key c)]]))]) ]]) (defroutes tstr (GET "/" ((html-doc "Sample" create-table))) (ANY "*" 404)) That outputs the table with the sections (salaried, manager, etc) and the names in the sections, I just feel like I'm abusing the domap by nesting it too many times as I'll probably need to add more domaps just to get the shift times in their proper columns and the code is getting a 'dirty' feel to it. I apologize in advance if I'm not including enough information, I don't normally ask for help on coding, also this is my 1st SO question :). If you know any better approaches to do this or even tips or tricks I should know as a newbie, they are definitely welcome. Thanks.

    Read the article

  • How can I do batch image processing with ImageJ in Java or clojure?

    - by Robert McIntyre
    I want to use ImageJ to do some processing of several thousand images. Is there a way to take any general imageJ plugin and apply it to hundreds of images automatically? For example, say I want to take my thousand images and apply a polar transformation to each--- A polar transformation plugin for ImageJ can be found here: http://rsbweb.nih.gov/ij/plugins/polar-transformer.html Great! Let's use it. From: [http://albert.rierol.net/imagej_programming_tutorials.html#How%20to%20automate%20an%20ImageJ%20dialog] I find that I can apply a plugin using the following: (defn x-polar [imageP] (let [thread (Thread/currentThread) options ""] (.setName thread "Run$_polar-transform") (Macro/setOptions thread options) (IJ/runPlugIn imageP "Polar_Transformer" ""))) This is good because it suppresses the dialog which would otherwise pop up for every image. But running this always brings up a window containing the transformed image, when what I want is to simply return the transformed image. The stupidest way to do what I want is to just close the window that comes up and return the image which it was displaying. Does what I want but is absolutely retarded: (defn x-polar [imageP] (let [thread (Thread/currentThread) options ""] (.setName thread "Run$_polar-transform") (Macro/setOptions thread options) (IJ/runPlugIn imageP "Polar_Transformer" "") (let [return-image (IJ/getImage)] (.hide return-image) return-image))) I'm obviously missing something about how to use imageJ plugins in a programming context. Does anyone know the right way to do this? Thanks, --Robert McIntyre

    Read the article

  • How can I do batch image processing with ImageJ in clojure?

    - by Robert McIntyre
    I want to use ImageJ to do some processing of several thousand images. Is there a way to take any general imageJ plugin and apply it to hundreds of images automatically? For example, say I want to take my thousand images and apply a polar transformation to each--- A polar transformation plugin for ImageJ can be found here: http://rsbweb.nih.gov/ij/plugins/polar-transformer.html Great! Let's use it. From: [http://albert.rierol.net/imagej_programming_tutorials.html#How%20to%20automate%20an%20ImageJ%20dialog] I find that I can apply a plugin using the following: (defn x-polar [imageP] (let [thread (Thread/currentThread) options ""] (.setName thread "Run$_polar-transform") (Macro/setOptions thread options) (IJ/runPlugIn imageP "Polar_Transformer" ""))) This is good because it suppresses the dialog which would otherwise pop up for every image. But running this always brings up a window containing the transformed image, when what I want is to simply return the transformed image. The stupidest way to do what I want is to just close the window that comes up and return the image which it was displaying. Does what I want but is absolutely retarded: (defn x-polar [imageP] (let [thread (Thread/currentThread) options ""] (.setName thread "Run$_polar-transform") (Macro/setOptions thread options) (IJ/runPlugIn imageP "Polar_Transformer" "") (let [return-image (IJ/getImage)] (.hide return-image) return-image))) I'm obviously missing something about how to use imageJ plugins in a programming context. Does anyone know the right way to do this? Thanks, --Robert McIntyre

    Read the article

  • Project Euler #14 and memoization in Clojure

    - by dbyrne
    As a neophyte clojurian, it was recommended to me that I go through the Project Euler problems as a way to learn the language. Its definitely a great way to improve your skills and gain confidence. I just finished up my answer to problem #14. It works fine, but to get it running efficiently I had to implement some memoization. I couldn't use the prepackaged memoize function because of the way my code was structured, and I think it was a good experience to roll my own anyways. My question is if there is a good way to encapsulate my cache within the function itself, or if I have to define an external cache like I have done. Also, any tips to make my code more idiomatic would be appreciated. (use 'clojure.test) (def mem (atom {})) (with-test (defn chain-length ([x] (chain-length x x 0)) ([start-val x c] (if-let [e (last(find @mem x))] (let [ret (+ c e)] (swap! mem assoc start-val ret) ret) (if (<= x 1) (let [ret (+ c 1)] (swap! mem assoc start-val ret) ret) (if (even? x) (recur start-val (/ x 2) (+ c 1)) (recur start-val (+ 1 (* x 3)) (+ c 1))))))) (is (= 10 (chain-length 13)))) (with-test (defn longest-chain ([] (longest-chain 2 0 0)) ([c max start-num] (if (>= c 1000000) start-num (let [l (chain-length c)] (if (> l max) (recur (+ 1 c) l c) (recur (+ 1 c) max start-num)))))) (is (= 837799 (longest-chain))))

    Read the article

  • Trouble with building up a string in Clojure

    - by Aki Iskandar
    Hi gang - [this may seem like my problem is with Compojure, but it isn't - it's with Clojure] I've been pulling my hair out on this seemingly simple issue - but am getting nowhere. I am playing with Compojure (a light web framework for Clojure) and I would just like to generate a web page showing showing my list of todos that are in a PostgreSQL database. The code snippets are below (left out the database connection, query, etc - but that part isn't needed because specific issue is that the resulting HTML shows nothing between the <body> and </body> tags). As a test, I tried hard-coding the string in the call to main-layout, like this: (html (main-layout "Aki's Todos" "Haircut<br>Study Clojure<br>Answer a question on Stackoverfolw")) - and it works fine. So the real issue is that I do not believe I know how to build up a string in Clojure. Not the idiomatic way, and not by calling out to Java's StringBuilder either - as I have attempted to do in the code below. A virtual beer, and a big upvote to whoever can solve it! Many thanks! ============================================================= ;The master template (a very simple POC for now, but can expand on it later) (defn main-layout "This is one of the html layouts for the pages assets - just like a master page" [title body] (html [:html [:head [:title title] (include-js "todos.js") (include-css "todos.css")] [:body body]])) (defn show-all-todos "This function will generate the todos HTML table and call the layout function" [] (let [rs (select-all-todos) sbHTML (new StringBuilder)] (for [rec rs] (.append sbHTML (str rec "<br><br>"))) (html (main-layout "Aki's Todos" (.toString sbHTML))))) ============================================================= Again, the result is a web page but with nothing between the body tags. If I replace the code in the for loop with println statements, and direct the code to the repl - forgetting about the web page stuff (ie. the call to main-layout), the resultset gets printed - BUT - the issue is with building up the string. Thanks again. ~Aki

    Read the article

  • Should not a tail-recursive function also be faster?

    - by Balint Erdi
    I have the following Clojure code to calculate a number with a certain "factorable" property. (what exactly the code does is secondary). (defn factor-9 ([] (let [digits (take 9 (iterate #(inc %) 1)) nums (map (fn [x] ,(Integer. (apply str x))) (permutations digits))] (some (fn [x] (and (factor-9 x) x)) nums))) ([n] (or (= 1 (count (str n))) (and (divisible-by-length n) (factor-9 (quot n 10)))))) Now, I'm into TCO and realize that Clojure can only provide tail-recursion if explicitly told so using the recur keyword. So I've rewritten the code to do that (replacing factor-9 with recur being the only difference): (defn factor-9 ([] (let [digits (take 9 (iterate #(inc %) 1)) nums (map (fn [x] ,(Integer. (apply str x))) (permutations digits))] (some (fn [x] (and (factor-9 x) x)) nums))) ([n] (or (= 1 (count (str n))) (and (divisible-by-length n) (recur (quot n 10)))))) To my knowledge, TCO has a double benefit. The first one is that it does not use the stack as heavily as a non tail-recursive call and thus does not blow it on larger recursions. The second, I think is that consequently it's faster since it can be converted to a loop. Now, I've made a very rough benchmark and have not seen any difference between the two implementations although. Am I wrong in my second assumption or does this have something to do with running on the JVM (which does not have automatic TCO) and recur using a trick to achieve it? Thank you.

    Read the article

  • Any merit to a lazy-ish juxt function?

    - by NielsK
    In answering a question about a function that maps over multiple functions with the same arguments (A: juxt), I came up with a function that basically took the same form as juxt, but used map: (defn could-be-lazy-juxt [& funs] (fn [& args] (map #(apply %1 %2) funs (repeat args)))) => ((juxt inc dec str) 1) [2 0 "1"] => ((could-be-lazy-juxt inc dec str) 1) (2 0 "1") => ((juxt * / -) 6 2) [12 3 4] => ((could-be-lazy-juxt * / -) 6 2) (12 3 4) As posted in the original question, I have little clue about the laziness or performance of it, but timing in the REPL does suggest something lazy-ish is going on. => (time (apply (juxt + -) (range 1 100))) "Elapsed time: 0.097198 msecs" [4950 -4948] => (time (apply (could-be-lazy-juxt + -) (range 1 100))) "Elapsed time: 0.074558 msecs" (4950 -4948) => (time (apply (juxt + -) (range 10000000))) "Elapsed time: 1019.317913 msecs" [49999995000000 -49999995000000] => (time (apply (could-be-lazy-juxt + -) (range 10000000))) "Elapsed time: 0.070332 msecs" (49999995000000 -49999995000000) I'm sure this function is not really that quick (the print of the outcome 'feels' about as long in both). Doing a 'take x' on the function only limits the amount of functions evaluated, which probably is limited in it's applicability, and limiting the other parameters by 'take' should be just as lazy in normal juxt. Is this juxt really lazy ? Would a lazy juxt bring anything useful to the table, for instance as a compositing step between other lazy functions ? What are the performance (mem / cpu / object count / compilation) implications ? Is that why the Clojure juxt implementation is done with a reduce and returns a vector ? Edit: Somehow things can always be done simpler in Clojure. (defn could-be-lazy-juxt [& funs] (fn [& args] (map #(apply % args) funs)))

    Read the article

  • Is it bad form to stage a function's steps in intermediate variables (let bindings)?

    - by octopusgrabbus
    I find I tend to need intermediate variables. In Clojure that's in the form of let bindings, like cmp-result-1 and cmp-result-2 in the following function. (defn str-cmp "Takes two strings and compares them. Returns the string if a match; and nil if not." [str-1 str-2 start-pos substr-len] (let [cmp-result-1 (subs str-1 start-pos substr-len) cmp-result-2 (subs str-2 start-pos substr-len)] (compare cmp-result-1 cmp-result-2))) I could re-write this function without them, but to me, the function's purpose looks clearer. I tend to do this quite in a bit in my main, and that is primarily for debugging purposes, so I can pass a variable to print out intermediate output. Is this bad form, and, if so, why? Thanks.

    Read the article

  • Creating a Lazy Sequence of Directory Descendants in C#

    My dear friend Craig Andera posted an implementation of a function that descends into a directory in a "lazy" manner, i.e. you get the first descendant back right away and not after all descendants have been calculated. His implementation was in Clojure, a Lisp variant that runs on the Java VM: (import [java.io File])(defn dir-descendants [dir]  (let [children (.listFiles (File. dir))]    (lazy-cat      (map (memfn getPath) (filter (memfn isFile) children))...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    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

  • Sum function doesn't work :/

    - by StackedCrooked
    A while ago this code seemed to work, but now it doesn't anymore. Is there something wrong with it? user=> (defn sum [a b] (a + b)) #'user/sum user=> (sum 3 4) java.lang.ClassCastException: java.lang.Integer cannot be cast to clojure.lang.IFn (NO_SOURCE_FILE:0) user=> It's probably time to take a break :)

    Read the article

  • How can I add imports to an "eval"ed piece of clojure code?

    - by Zubair
    I would like to evaluate some clojure code entered by users interactively, and I would like to "use" certain namespaces and "import" certain Java classes as well. I end up running the code using: (defn execute-command [string-command] let [ code-with-context (add-code-context string-command) result (eval(read-string code-with-context)) ] result ) My question is how can I program "add-code-context" to add the required context to the code in "string-command"?

    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

  • testing Clojure in Maven

    - by Ralph
    I am new at Maven and even newer at Clojure. As an exercise to learn the language, I am writing a spider solitaire player program. I also plan on writing a similar program in Scala to compare the implementations (see my post http://stackoverflow.com/questions/2571267/modern-java-alternatives-closed). I have configured a Maven directory structure containing the usual src/main/clojure and src/test/clojure directories. My pom.xml file includes the clojure-maven-plugin. When I run "mvn test", it displays "No tests to run", despite my having test code in the src/test/clojure directory. As I misnaming something? Here is my pom.xml file: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SpiderPlayer</groupId> <artifactId>SpiderPlayer</artifactId> <version>1.0.0-SNAPSHOT</version> <inceptionYear>2010</inceptionYear> <packaging>jar</packaging> <properties> <maven.build.timestamp.format>yyMMdd.HHmm</maven.build.timestamp.format> <main.dir>org/dogdaze/spider_player</main.dir> <main.package>org.dogdaze.spider_player</main.package> <main.class>${main.package}.Main</main.class> </properties> <build> <sourceDirectory>src/main/clojure</sourceDirectory> <testSourceDirectory>src/main/clojure</testSourceDirectory> <plugins> <plugin> <groupId>com.theoryinpractise</groupId> <artifactId>clojure-maven-plugin</artifactId> <version>1.3.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.3</version> <executions> <execution> <goals> <goal>run</goal> </goals> <phase>generate-sources</phase> <configuration> <tasks> <echo file="${project.build.sourceDirectory}/${main.dir}/Version.clj" message="(ns ${main.package})${line.separator}"/> <echo file="${project.build.sourceDirectory}/${main.dir}/Version.clj" append="true" message="(def version &quot;${maven.build.timestamp}&quot;)${line.separator}"/> </tasks> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>2.1</version> <executions> <execution> <goals> <goal>single</goal> </goals> <phase>package</phase> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <mainClass>${main.class}</mainClass> </manifest> </archive> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <redirectTestOutputToFile>true</redirectTestOutputToFile> <skipTests>false</skipTests> <skip>false</skip> </configuration> <executions> <execution> <id>surefire-it</id> <phase>integration-test</phase> <goals> <goal>test</goal> </goals> <configuration> <skip>false</skip> </configuration> </execution> </executions> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>commons-cli</groupId> <artifactId>commons-cli</artifactId> <version>1.2</version> <scope>compile</scope> </dependency> </dependencies> </project> Here is my Clojure source file (src/main/clojure/org/dogdaze/spider_player/Deck.clj): ; Copyright 2010 Dogdaze (ns org.dogdaze.spider_player.Deck (:use [clojure.contrib.seq-utils :only (shuffle)])) (def suits [:clubs :diamonds :hearts :spades]) (def ranks [:ace :two :three :four :five :six :seven :eight :nine :ten :jack :queen :king]) (defn suit-seq "Return 4 suits: if number-of-suits == 1: :clubs :clubs :clubs :clubs if number-of-suits == 2: :clubs :diamonds :clubs :diamonds if number-of-suits == 4: :clubs :diamonds :hearts :spades." [number-of-suits] (take 4 (cycle (take number-of-suits suits)))) (defstruct card :rank :suit) (defn unshuffled-deck "Create an unshuffled deck containing all cards from the number of suits specified." [number-of-suits] (for [rank ranks suit (suit-seq number-of-suits)] (struct card rank suit))) (defn deck "Create a shuffled deck containing all cards from the number of suits specified." [number-of-suits] (shuffle (unshuffled-deck number-of-suits))) Here is my test case (src/test/clojure/org/dogdaze/spider_player/TestDeck.clj): ; Copyright 2010 Dogdaze (ns org.dogdaze.spider_player (:use clojure.set clojure.test org.dogdaze.spider_player.Deck)) (deftest test-suit-seq (is (= (suit-seq 1) [:clubs :clubs :clubs :clubs])) (is (= (suit-seq 2) [:clubs :diamonds :clubs :diamonds])) (is (= (suit-seq 4) [:clubs :diamonds :hearts :spades]))) (def one-suit-deck [{:rank :ace, :suit :clubs} {:rank :ace, :suit :clubs} {:rank :ace, :suit :clubs} {:rank :ace, :suit :clubs} {:rank :two, :suit :clubs} {:rank :two, :suit :clubs} {:rank :two, :suit :clubs} {:rank :two, :suit :clubs} {:rank :three, :suit :clubs} {:rank :three, :suit :clubs} {:rank :three, :suit :clubs} {:rank :three, :suit :clubs} {:rank :four, :suit :clubs} {:rank :four, :suit :clubs} {:rank :four, :suit :clubs} {:rank :four, :suit :clubs} {:rank :five, :suit :clubs} {:rank :five, :suit :clubs} {:rank :five, :suit :clubs} {:rank :five, :suit :clubs} {:rank :six, :suit :clubs} {:rank :six, :suit :clubs} {:rank :six, :suit :clubs} {:rank :six, :suit :clubs} {:rank :seven, :suit :clubs} {:rank :seven, :suit :clubs} {:rank :seven, :suit :clubs} {:rank :seven, :suit :clubs} {:rank :eight, :suit :clubs} {:rank :eight, :suit :clubs} {:rank :eight, :suit :clubs} {:rank :eight, :suit :clubs} {:rank :nine, :suit :clubs} {:rank :nine, :suit :clubs} {:rank :nine, :suit :clubs} {:rank :nine, :suit :clubs} {:rank :ten, :suit :clubs} {:rank :ten, :suit :clubs} {:rank :ten, :suit :clubs} {:rank :ten, :suit :clubs} {:rank :jack, :suit :clubs} {:rank :jack, :suit :clubs} {:rank :jack, :suit :clubs} {:rank :jack, :suit :clubs} {:rank :queen, :suit :clubs} {:rank :queen, :suit :clubs} {:rank :queen, :suit :clubs} {:rank :queen, :suit :clubs} {:rank :king, :suit :clubs} {:rank :king, :suit :clubs} {:rank :king, :suit :clubs} {:rank :king, :suit :clubs}]) (def two-suits-deck [{:rank :ace, :suit :clubs} {:rank :ace, :suit :diamonds} {:rank :ace, :suit :clubs} {:rank :ace, :suit :diamonds} {:rank :two, :suit :clubs} {:rank :two, :suit :diamonds} {:rank :two, :suit :clubs} {:rank :two, :suit :diamonds} {:rank :three, :suit :clubs} {:rank :three, :suit :diamonds} {:rank :three, :suit :clubs} {:rank :three, :suit :diamonds} {:rank :four, :suit :clubs} {:rank :four, :suit :diamonds} {:rank :four, :suit :clubs} {:rank :four, :suit :diamonds} {:rank :five, :suit :clubs} {:rank :five, :suit :diamonds} {:rank :five, :suit :clubs} {:rank :five, :suit :diamonds} {:rank :six, :suit :clubs} {:rank :six, :suit :diamonds} {:rank :six, :suit :clubs} {:rank :six, :suit :diamonds} {:rank :seven, :suit :clubs} {:rank :seven, :suit :diamonds} {:rank :seven, :suit :clubs} {:rank :seven, :suit :diamonds} {:rank :eight, :suit :clubs} {:rank :eight, :suit :diamonds} {:rank :eight, :suit :clubs} {:rank :eight, :suit :diamonds} {:rank :nine, :suit :clubs} {:rank :nine, :suit :diamonds} {:rank :nine, :suit :clubs} {:rank :nine, :suit :diamonds} {:rank :ten, :suit :clubs} {:rank :ten, :suit :diamonds} {:rank :ten, :suit :clubs} {:rank :ten, :suit :diamonds} {:rank :jack, :suit :clubs} {:rank :jack, :suit :diamonds} {:rank :jack, :suit :clubs} {:rank :jack, :suit :diamonds} {:rank :queen, :suit :clubs} {:rank :queen, :suit :diamonds} {:rank :queen, :suit :clubs} {:rank :queen, :suit :diamonds} {:rank :king, :suit :clubs} {:rank :king, :suit :diamonds} {:rank :king, :suit :clubs} {:rank :king, :suit :diamonds}]) (def four-suits-deck [{:rank :ace, :suit :clubs} {:rank :ace, :suit :diamonds} {:rank :ace, :suit :hearts} {:rank :ace, :suit :spades} {:rank :two, :suit :clubs} {:rank :two, :suit :diamonds} {:rank :two, :suit :hearts} {:rank :two, :suit :spades} {:rank :three, :suit :clubs} {:rank :three, :suit :diamonds} {:rank :three, :suit :hearts} {:rank :three, :suit :spades} {:rank :four, :suit :clubs} {:rank :four, :suit :diamonds} {:rank :four, :suit :hearts} {:rank :four, :suit :spades} {:rank :five, :suit :clubs} {:rank :five, :suit :diamonds} {:rank :five, :suit :hearts} {:rank :five, :suit :spades} {:rank :six, :suit :clubs} {:rank :six, :suit :diamonds} {:rank :six, :suit :hearts} {:rank :six, :suit :spades} {:rank :seven, :suit :clubs} {:rank :seven, :suit :diamonds} {:rank :seven, :suit :hearts} {:rank :seven, :suit :spades} {:rank :eight, :suit :clubs} {:rank :eight, :suit :diamonds} {:rank :eight, :suit :hearts} {:rank :eight, :suit :spades} {:rank :nine, :suit :clubs} {:rank :nine, :suit :diamonds} {:rank :nine, :suit :hearts} {:rank :nine, :suit :spades} {:rank :ten, :suit :clubs} {:rank :ten, :suit :diamonds} {:rank :ten, :suit :hearts} {:rank :ten, :suit :spades} {:rank :jack, :suit :clubs} {:rank :jack, :suit :diamonds} {:rank :jack, :suit :hearts} {:rank :jack, :suit :spades} {:rank :queen, :suit :clubs} {:rank :queen, :suit :diamonds} {:rank :queen, :suit :hearts} {:rank :queen, :suit :spades} {:rank :king, :suit :clubs} {:rank :king, :suit :diamonds} {:rank :king, :suit :hearts} {:rank :king, :suit :spades}]) (deftest test-unshuffled-deck (is (= (unshuffled-deck 1) one-suit-deck)) (is (= (unshuffled-deck 2) two-suits-deck)) (is (= (unshuffled-deck 4) four-suits-deck))) (deftest test-shuffled-deck (is (= (set (deck 1)) (set one-suit-deck))) (is (= (set (deck 2)) (set two-suits-deck))) (is (= (set (deck 4)) (set four-suits-deck)))) (run-tests) Any idea why the test is not running? BTW, feel free to suggest improvements to the Clojure code. Thanks, Ralph

    Read the article

  • What is up with the Joy of Clojure 2nd edition?

    - by kurofune
    Manning just released the second edition of the beloved Joy of Clojure book, and while I share that love I get the feeling that many of the examples are already outdated. In particular, in the chapter on optimization the recommended type-hinting seems not to be allowed by the compiler. I don't know if this was allowable for older versions of Clojure. For example: (defn factorial-f [^long original-x] (loop [x original-x, acc 1] (if (>= 1 x) acc (recur (dec x) (*' x acc))))) returns: clojure.lang.Compiler$CompilerException: java.lang.UnsupportedOperationException: Can't type hint a primitive local, compiling:(null:3:1) Likewise, the chapter on core.logic seems be using an old API and I have to find workarounds for each example to accommodate the recent changes. For example, I had to turn this: (logic/defrel orbits orbital body) (logic/fact orbits :mercury :sun) (logic/fact orbits :venus :sun) (logic/fact orbits :earth :sun) (logic/fact orbits :mars :sun) (logic/fact orbits :jupiter :sun) (logic/fact orbits :saturn :sun) (logic/fact orbits :uranus :sun) (logic/fact orbits :neptune :sun) (logic/run* [q] (logic/fresh [orbital body] (orbits orbital body) (logic/== q orbital))) into this, leveraging the pldb lib: (pldb/db-rel orbits orbital body) (def facts (pldb/db [orbits :mercury :sun] [orbits :venus :sun] [orbits :earth :sun] [orbits :mars :sun] [orbits :jupiter :sun] [orbits :saturn :sun] [orbits :uranus :sun] [orbits :neptune :sun])) (pldb/with-db facts (logic/run* [q] (logic/fresh [orbital body] (orbits orbital body) (logic/== q orbital)))) I am still pulling teeth to get the later examples to work. I am relatively new programming, myself, so I wonder if I am naively looking over something here, or are if these points I'm making legitimate concerns? I really want to get good at this stuff like type-hinting and core.logic, but wanna make sure I am studying up to date materials. Any illuminating facts to help clear up my confusion would be most welcome.

    Read the article

  • Why does PuTTYcyg display â instead of hyphen in man pages?

    - by gbacon
    I've been using PuTTYcyg as a Cygwin terminal, but it doesn't render dashes in manual pages correctly. For example, the top of man gcc looks like GCC(1) GNU GCC(1) NAME gcc â GNU project C and C++ compiler SYNOPSIS gcc [âc|âS|âE] [âstd=standard] [âg] [âpg] [âOlevel] [âWwarn...] [âpedantic] [âIdir...] [âLdir...] [âDmacro[=defn]...] [âUmacro] [âfoption...] [âmmachineâoption...] [âo outfile] infile... Changing fonts doesn't help. How can I fix this?

    Read the article

  • When and how should custom hierarchies be used in clojure?

    - by Rob Lachlan
    Clojure's system for creating an ad hoc hierarchy of keywords is familiar to most people who have spent a bit of time with the language. For example, most demos and presentations of the language include examples such as (derive ::child ::parent) and they go on to show how this can be used for multi-method dispatch. In all of the slides and presentations that I've seen, they use the global hierarchy. But it is possible to keyword relationships in custom hierarchies. Some questions, therefore: Are there any guidelines on when this is useful or necessary? Are there any functions for manipulating hierarchies? Merging is particularly useful, so I do this: (defn merge-h [& hierarchies] (apply merge-with (cons #(merge-with clojure.set/union %1 %2) hierarchies)) But I was wondering if such functions already exist somewhere.

    Read the article

  • In Clojure - How do I access keys in a vector of structs

    - by Nick
    I have the following vector of structs: (defstruct #^{:doc "Basic structure for book information."} book :title :authors :price) (def #^{:doc "The top ten Amazon best sellers on 16 Mar 2010."} best-sellers [(struct book "The Big Short" ["Michael Lewis"] 15.09) (struct book "The Help" ["Kathryn Stockett"] 9.50) (struct book "Change Your Prain, Change Your Body" ["Daniel G. Amen M.D."] 14.29) (struct book "Food Rules" ["Michael Pollan"] 5.00) (struct book "Courage and Consequence" ["Karl Rove"] 16.50) (struct book "A Patriot's History of the United States" ["Larry Schweikart","Michael Allen"] 12.00) (struct book "The 48 Laws of Power" ["Robert Greene"] 11.00) (struct book "The Five Thousand Year Leap" ["W. Cleon Skousen","James Michael Pratt","Carlos L Packard","Evan Frederickson"] 10.97) (struct book "Chelsea Chelsea Bang Bang" ["Chelsea Handler"] 14.03) (struct book "The Kind Diet" ["Alicia Silverstone","Neal D. Barnard M.D."] 16.00)]) I would like to sum the prices of all the books in the vector. What I have is the following: (defn get-price "Same as print-book but handling multiple authors on a single book" [ {:keys [title authors price]} ] price) Then I: (reduce + (map get-price best-sellers)) Is there a way of doing this without mapping the "get-price" function over the vector? Or is there an idiomatic way of approaching this problem?

    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 - 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

  • Unicode identifiers in Python?

    - by viksit
    Hi all, I want to build a Python function that calculates, and would like to name my summation function S. In a similar fashion, would like to use ? for product, and so on. I was wondering if there was a way to name a python function in this fashion? def S (..): .. .. That is, does Python support unicode identifiers, and if so, could someone provide an example for it? Thanks! Original motivation for this was a piece of Clojure code I saw today that looks like, (defn entropy [X] (* -1 (S [i X] (* (p i) (log (p i)))))) where S is a macro defined as, (defmacro S ... ) and I thought that was pretty cool.

    Read the article

  • Clojure: Testing every value from map operation for truth

    - by Ralph
    How can I test that every value in the collection returned by map is true? I am using the following: (defn test [f coll] (every? #(identity %) (map f coll))) with the anonymous function #(identity %), but I was wondering if there is a better way. I cannot use (apply and ...) because and is a macro. UPDATE: BTW, I am making my way through The Haskell Road to Logic, Maths, and Programming, by Kees Doets and Jan can Eijck, but doing the exercises in Clojure. It's a very interesting book.

    Read the article

< Previous Page | 1 2 3  | Next Page >