Search Results

Search found 365 results on 15 pages for 'clojure'.

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

  • 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

  • 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

  • Vectors or Java arrays for Tetris?

    - by StackedCrooked
    I'm trying to create a Tetris-like game with Clojure and I'm having some trouble deciding the data structure for the playing field. I want to define the playing field as a mutable grid. The individual blocks are also grids, but don't need to be mutable. My first attempt was to define a grid as a vector of vectors. For example an S-block looks like this: :s-block { :grids [ [ [ 0 1 1 ] [ 1 1 0 ] ] [ [ 1 0 ] [ 1 1 ] [ 0 1 ] ] ] } But that turns out to be rather tricky for simple things like iterating and painting (see the code below). For making the grid mutable my initial idea was to make each row a reference. But then I couldn't really figure out how to change the value of a specific cell in a row. One option would have been to create each individual cell a ref instead of each row. But that feels like an unclean approach. I'm considering using Java arrays now. Clojure's aget and aset functions will probably turn out to be much simpler. However before digging myself in a deeper mess I want to ask ideas/insights. How would you recommend implementing a mutable 2d grid? Feel free to share alternative approaches as well. Source code current state: Tetris.clj (rev452)

    Read the article

  • How to remove list of words from strings

    - by zeljko
    What I would like to do (in Clojure): For example, I have a vector of words that need to be removed: (def forbidden-words [":)" "the" "." "," " " ...many more...]) ... and a vector of strings: (def strings ["the movie list" "this.is.a.string" "haha :)" ...many more...]) So, each forbidden word should be removed from each string, and the result, in this case, would be: ["movie list" "thisisastring" "haha"]. How to do this ?

    Read the article

  • Why are so many new languages written for the Java VM?

    - by sdudo
    There are more and more programming languages (Scala, Clojure,...) coming out that are made for the Java VM and are therefore compatible with the Java Byte-Code. I'm beginning to ask myself: Why the Java VM? What makes it so powerful or popular that there are new programming languages, which seem gaining popularity too, created for it? Why don't they write a new VM for a new language?

    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

  • IllegalAccessError and proxy

    - by konr
    Hi there, I'm translating this code to Clojure. As you can see, I have to extend the class ArthurFrame, yet I'm getting an IllegalAccessError everytime I use (proxy [ArthurFrame] [] ...). Any idea why? Here is the class's source. Thanks!

    Read the article

  • What is the difference between 1 and '1 in Lisp?

    - by Jason Baker
    I had never really thought about whether a symbol could be a number in Lisp, so I played around with it today: > '1 1 > (+ '1 '1) 2 > (+ '1 1) 2 > (define a '1) > (+ a 1) 2 The above code is scheme, but it seems to be roughly the same in Common Lisp and Clojure as well. Is there any difference between 1 and quoted 1?

    Read the article

  • Why is the Java VM so popular?

    - by sdudo
    There are more and more programming languages (Scala, Clojure,...) coming out that are made for the Java VM and are therefore compatible with the Java Byte-Code. I'm beginning to ask myself: Why the Java VM? What makes it so powerful or popular that there are new programming languages, which seem gaining popularity too, created for it? Why don't they write a new VM for a new language?

    Read the article

  • Installing Enclosure with Netbeans

    - by jdknewb
    Hi all, I am having trouble installing Enclosure and getting it to work. I have followed this guide http://www.enclojure.org/gettingstarted and successfully installed Enclosure (I think). However, when I try to build the sample application (labrepl) I get a bunch of errors and a failed build. I haven't used Java in a long time and I've never used Netbeans, and the error doesn't seem very helpful with my limited knowledge of this domain. I'm using the latest Netbeans and the Enclosure URL from the guide. Since I am on Windows, I can't use git to clone the repo, so I'm not sure what to do from here. Anyway, here are the error messages. WARNING: You are running embedded Maven builds, some build may fail due to incompatibilities with latest Maven release. To set Maven instance to use for building, click here. Scanning for projects... [#process-resources] [resources:resources] Using default encoding to copy filtered resources. [#compile] [ERROR]Transitive dependency resolution for scope: compile has failed for your project. [ERROR]Error message: Missing: [ERROR]---------- [ERROR]1) org.clojure:clojure-contrib:jar:1.2.0-master-SNAPSHOT [ERROR] Try downloading the file manually from the project website. [ERROR] Then, install it using the command: [ERROR] mvn install:install-file -DgroupId=org.clojure -DartifactId=clojure-contrib -Dversion=1.2.0-master-SNAPSHOT -Dpackaging=jar -Dfile=/path/to/file [ERROR] Alternatively, if you host your own repository you can deploy the file there: [ERROR] mvn deploy:deploy-file -DgroupId=org.clojure -DartifactId=clojure-contrib -Dversion=1.2.0-master-SNAPSHOT -Dpackaging=jar -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id] [ERROR] Path to dependency: [ERROR] 1) labrepl:labrepl:jar:0.0.1 [ERROR] 2) org.clojure:clojure-contrib:jar:1.2.0-master-SNAPSHOT [ERROR]---------- [ERROR]1 required artifact is missing. [ERROR]for artifact: [ERROR] labrepl:labrepl:jar:0.0.1 [ERROR]from the specified remote repositories: [ERROR] central (http://repo1.maven.org/maven2), [ERROR] clojars (http://clojars.org/repo/), [ERROR] incanter (http://repo.incanter.org), [ERROR] clojure-snapshots (http://build.clojure.org/snapshots), [ERROR] clojure (http://build.clojure.org/releases), [ERROR] clojure-releases (http://build.clojure.org/releases) [ERROR]Group-Id: labrepl [ERROR]Artifact-Id: labrepl [ERROR]Version: 0.0.1 [ERROR]From file: C:\Users\chloey\Documents\NetBeansProjects\RelevanceLabRepl\pom.xml ------------------------------------------------------------------------ For more information, run with the -e flag ------------------------------------------------------------------------ BUILD FAILED ------------------------------------------------------------------------ Total time: 1 second Finished at: Wed Jun 09 21:53:04 CDT 2010 Final Memory: 72M/172M ------------------------------------------------------------------------ Thanks all.

    Read the article

  • Override `drop` for a custom sequence

    - by Bruno Reis
    In short: in Clojure, is there a way to redefine a function from the standard sequence API (which is not defined on any interface like ISeq, IndexedSeq, etc) on a custom sequence type I wrote? 1. Huge data files I have big files in the following format: A long (8 bytes) containing the number n of entries n entries, each one being composed of 3 longs (ie, 24 bytes) 2. Custom sequence I want to have a sequence on these entries. Since I cannot usually hold all the data in memory at once, and I want fast sequential access on it, I wrote a class similar to the following: (deftype DataSeq [id ^long cnt ^long i cached-seq] clojure.lang.IndexedSeq (index [_] i) (count [_] (- cnt i)) (seq [this] this) (first [_] (first cached-seq)) (more [this] (if-let [s (next this)] s '())) (next [_] (if (not= (inc i) cnt) (if (next cached-seq) (DataSeq. id cnt (inc i) (next cached-seq)) (DataSeq. id cnt (inc i) (with-open [f (open-data-file id)] ; open a memory mapped byte array on the file ; seek to the exact position to begin reading ; decide on an optimal amount of data to read ; eagerly read and return that amount of data )))))) The main idea is to read ahead a bunch of entries in a list and then consume from that list. Whenever the cache is completely consumed, if there are remaining entries, they are read from the file in a new cache list. Simple as that. To create an instance of such a sequence, I use a very simple function like: (defn ^DataSeq load-data [id] (next (DataSeq. id (count-entries id) -1 []))) ; count-entries is a trivial "open file and read a long" memoized As you can see, the format of the data allowed me to implement count in very simply and efficiently. 3. drop could be O(1) In the same spirit, I'd like to reimplement drop. The format of these data files allows me to reimplement drop in O(1) (instead of the standard O(n)), as follows: if dropping less then the remaining cached items, just drop the same amount from the cache and done; if dropping more than cnt, then just return the empty list. otherwise, just figure out the position in the data file, jump right into that position, and read data from there. My difficulty is that drop is not implemented in the same way as count, first, seq, etc. The latter functions call a similarly named static method in RT which, in turn, calls my implementation above, while the former, drop, does not check if the instance of the sequence it is being called on provides a custom implementation. Obviously, I could provide a function named anything but drop that does exactly what I want, but that would force other people (including my future self) to remember to use it instead of drop every single time, which sucks. So, the question is: is it possible to override the default behaviour of drop? 4. A workaround (I dislike) While writing this question, I've just figured out a possible workaround: make the reading even lazier. The custom sequence would just keep an index and postpone the reading operation, that would happen only when first was called. The problem is that I'd need some mutable state: the first call to first would cause some data to be read into a cache, all the subsequent calls would return data from this cache. There would be a similar logic on next: if there's a cache, just next it; otherwise, don't bother populating it -- it will be done when first is called again. This would avoid unnecessary disk reads. However, this is still less than optimal -- it is still O(n), and it could easily be O(1). Anyways, I don't like this workaround, and my question is still open. Any thoughts? Thanks.

    Read the article

  • Using a javax.servlet.Filter with Compojure

    - by mikera
    I'm trying to build a simple web site using Clojure / Compojure and want to feed apply a servlet filter to the request / response (i.e. a standard javax.servlet.Filter instance). e.g. if the current source code is: (defroutes my-app (GET "/*" (html [:h1 "Hello Foo!!"])) ) I would like to add a filter like this: (defroutes my-app (GET "/*" (FILTER my-filter-name (html [:h1 "Hello Foo!!"]))) ) Where my-filter-name is some arbitrary instance of javax.servlet.Filter. Any idea how to do this effectively and elegantly?

    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

  • A regex to match a comma that isn't surrounded by quotes.

    - by Rayne
    I'm using Clojure, so this is in the context of Java regexes. Here is an example string: "{:a "ab,cd, efg", :b "ab,def, egf,", :c "Conjecture"}" The important bits are the commas after each string. I'd like to be able to replace them with newline characters with Java's replaceAll method. A regex that will match any comma that is not surrounded by quotes will do. If I'm not coming across well, please ask and I'll be happily to clarify anything. edit: sorry for the confusion in the title. I haven't been awake very long. String: {:a "ab, cd efg",} <-- In this example, the comma at the end would be matched, but the ones inside the quote would not.

    Read the article

  • Fibonacci Sequence using loop and recur

    - by AdamJMTech
    I am doing the Project Euler challenge in Clojure and I want to find the sum of all the even numbers in a fibonacci sequence up to a certain number. The code for a function that does this is below. I know there are quicker and easier ways of doing this, I am just experimenting with recursion using loop and recur. However the code doesn't seem to work it never returns an answer. (defn fib-even-sum [upto] (loop [previous 1 nxt 1 sum 0] (if (or (<= upto 1) (>= nxt upto)) sum) (if (= (mod nxt 2) 0) (recur nxt (+ previous nxt) (+ sum nxt)) (recur nxt (+ previous nxt) sum)))) I was not sure if I could do recur twice in the same loop or not. I'm not sure if this is causing the problem?

    Read the article

  • Recursive function causing a stack overflow

    - by dbyrne
    I am trying to write a simple sieve function to calculate prime numbers in clojure. I've seen this question about writing an efficient sieve function, but I am not to that point yet. Right now I am just trying to write a very simple (and slow) sieve. Here is what I have come up with: (defn sieve [potentials primes] (if-let [p (first potentials)] (recur (filter #(not= (mod % p) 0) potentials) (conj primes p)) primes)) For small ranges it works fine, but causes a stack overflow for large ranges: user=> (sieve (range 2 30) []) [2 3 5 7 11 13 17 19 23 29] user=> (sieve (range 2 15000) []) java.lang.StackOverflowError (NO_SOURCE_FILE:0) I thought that by using recur this would be a non-stack-consuming looping construct? What am I missing?

    Read the article

  • Atoms and references

    - by StackedCrooked
    According to the book Programming Clojure refs manage coordinated, synchronous changes to shared state and atoms manage uncoordinated, synchronous changes to shared state. If I understood correctly "coordinated" implies multiple changes are encapsulated as one atomic operation. If that is the case then it seems to me that coordination only requires using a dosync call. For example what is the difference between: (def i (atom 0)) (def j (atom 0)) (dosync (swap! i inc) (swap! j dec)) and: (def i (ref 0)) (def j (ref 0)) (dosync (alter i inc) (alter j dec))

    Read the article

  • Alternatives to java on android

    - by user84584
    Hello guys, I just got myself an android phone and I'm dying to start coding on it ! However I'm not a big java fan, although I can live with that, I would like to know if there're reasonable alternatives for the android virtual machine. I've done a medium sized project using clojure, however from the reviews I read, it's very slow when running on android. How about scala ? I read that some people did experiments with it in android, is it "fast enough" ? How big is the learning curve ? Cheers, Ze Maria

    Read the article

  • Ref to map vs. map to refs vs. multiple refs

    - by mikera
    I'm working on a GUI application in Swing+Clojure that requires various mutable pieces of data (e.g. scroll position, user data, filename, selected tool options etc.). I can see at least three different ways of handling this set of data: Create a ref to a map of all the data: (def data (ref { :filename "filename.xml" :scroll [0 0] })) Create a map of refs to the individual data elements: (def datamap { :filename (ref "filename.xml") :scroll (ref [0 0]) })) Create a separate ref for each in the namespace: (def scroll (ref [0 0])) (def filename (ref "filename.xml")) Note: This data will be accessed concurrently, e.g. by background processing threads or the Swing event handling thread. However there probably isn't a need for consistent transactional updates of multiple elements. What would be your recommended approach and why?

    Read the article

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