help with substitution model [Sicp], using Clojure

I am studying the sicp book, and I have a doubt with the substitution model of a procedure: (defn A [x,y] (cond (= y 0) 0 (= x 0) (* 2 y) (= y 1) 2 :else (A (- x 1) (A x (- y 1))))) This procedure is part of the exercise 1.10. If I run the function in REPL with the following parameters (A 1 10), the result is 1024. I decided to verify the result using the Substitution Model, but the result was 2048. This is the substitution model that I wrote. There i

Launch an existing EC2 instance using Clojure and Pallet

I have a few EC2 instances on AWS that are in a suspended state. I'd like to use pallet to start them up from a Clojure program (and ultimately put them back into suspend). I'm not finding how to do this anywhere in the docs or examples. I've been able to connect to my AWS service and get a list of instances (as a list of nodes) using (def awsservice (compute-service "aws-ec2" :identity "" :credential "")) (def nodelist (nodes awsservice)) Now how do I start up one of these existing nodes? B

Clojure, core.logic: listo

According to https://github.com/clojure/core.logic/wiki/Differences-from-The-Reasoned-Schemer core.logic supports listo. However, the following piece of code does not compile (ns test.chap03 (:refer-clojure :exclude [==]) (:use [clojure.core.logic])) (defn ex07 [] (run* [x] (listo `(a b ~x d)))) It complains: Exception: java.lang.RuntimeException: Unable to resolve symbol: listo in this context, compiling:(test/chap03.clj:8) Question: what is going on, and how do I get li

Scheme equivalent of print function in Clojure

I'm looking at Scheme (Dr-Scheme) coming from Clojure. In Clojure I can type (print 'a 'b 'c) and the print function figures out that this is an arbitrary number of non-string arguments and prints them out separated by a space. In Scheme the print function expects a single argument. Is there a way to get the equivalent of Clojure's print function in Scheme?

How to update records in a ref map in Clojure?

Given the following scenario: (defrecord Person [firstname lastname]) (def some-map (ref {})) (dosync (alter some-map conj {1 (Person. "john" "doe")}) (alter some-map conj {2 (Person. "jane" "jameson")})) To change the firstname of "joe" to "nick", I do the following: (dosync (alter some-map (fn [m] (assoc m 1 (assoc (m 1) :firstname "nick"))))) What is the idiomatic way of doing this in Clojure?

The very first clojure compiler?

Clojure is written mainly in Clojure, but there had to be a "first" version of a clojure compiler that was written in something else, presuably Java. Is the code of that compiler available anywhere? My interest is purely academic, not productional, I'd like to see the way that Rich Hickey handled the chicken/egg problem.

Clojure - Map through all levels

I'm trying to create a map function that goes through every element and applies an operation. It is simply like a the map function, but goes in depth. The function takes two args; one function and one for the arguments. Here is what I have so far: (defn go-through [op & args] (if-not (sequential? (first args)) (apply op args) (apply (partial map go-through op) args))) And I knew that the last line wouldn't work, even without calling it. But I don't know how any other way.

Clojure Combining LazySeqs into one collection of maps

I'm trying to combine a couple of LazySeqs into one collection of maps. ("a" "b" "c" ...) ("x" "y" "z" ...) into ({:key1 "a" :key2 "x"} {:key1 "b" :key2 "y"} ...) It is guaranteed that the LazySeqs are of the same length. What would be the functional way to do this?

Clojure Get all fields from a Datomic entity

The 'Embedded' section of the Datomic Queries and Rules document says: Query languages like SQL are oriented around a client-server model where, in a single conversaton, you are going to have to both: Answer your fundamental question, e.g. who bought socks this month. Recover any additional information required for reporting and processing, e.g. what are their names and email addresses. The latter is not really a query, it is just a mechanical navigation to related info

Clojure find the n-tuples of all integers below m whose sum is a prime

I am going through the Clojure in Action book and code similar to that below is given for a function that returns all pairs of numbers below m whose sum is a prime (assume prime? is given): (defn pairs-for-primes [m] (let [z (range 0 m)] (for [a z b z :when (prime? (+ a b))] (list a b)))) How would one generalize that to return the n-tuples of all numbers below m whose sum is a prime? (defn all-ntuples-below [n m] ...

Error when entering decimal number in clojure repl

When I enter user> (* 10 .5) in my clojure repl I get this message: CompilerException java.lang.RuntimeException: Unable to resolve symbol: .5 in this context, compiling:(NO_SOURCE_PATH:1:1) I know I can do this (/ 10 2) or (* 10 (/ 1 2)). Can anyone tell me what's going on here? I'm using clojure 1.5, emacs and nrepl

Clojure transferring values from remote nrepl

I have a remote nrepl which I started via Screen, that I connect to using lein repl :connect. Can I have a value transfer over to a local repl ? The reason I ask is that: Using Screen means I get headless exceptions when I want to do graphics operations and Sometimes I would like to get a local copy of a remote value to play with.

Clojure thinking objectively vs. functionally

As I try to increase my knowledge of functional programming, I'm finding it quite difficult to re-imagine the solutions to problems I've solved in an OOP language in terms of functions, particularly where widgets are involved. Sites like Project Euler and 4Clojure are great for learning core functions and techniques for manipulating primitive data, but what I'd really like is a resource that discusses how to idiomatically translate OOP constructs into FP, with particular attention to identifying

Retrieving maps from a sequence based on contents - Clojure

I have a data set in the format {:application "name1", :date "date1", :description "desc1"} {:application "name1", :date "date2", :description "desc2"} {:application "name2", :date "date1", :description "desc1"} {:application "name2", :date "date2", :description "desc2"} etc ...) My goal is to create a sequence containing the maps for an individual application, as below. {:application "name1", :date "date1", :description "desc1"} {:application "name1", :date "date2", :description "desc2"}

Clojure: Apply or to a list

This question similar to say, In clojure, how to apply 'and' to a list?, but solution doesn't apply to my question. every? function returns just a boolean value. or is a macro, so this code is invalid: (apply or [nil 10 20]) ; I want to get 10 here, as if 'or was a function. Using not-every? I will get just boolean value, but I want to preserve semantics of or - the "true" element should be a value of the expression. What is idiomatic way to do this? My idea so far: (first (drop-w

Clojure- Amending code for different functionality

This line of code: dates (distinct (map (keyword :cobdate) data)) had to be amended to this line of code dates (distinct (map #(get % "cobdate") data)) in order to use in the way I required Could anyone tell me how to convert this line of code: grouped-by-token (group-by :severity data) in order to make the same conversion?

Clojure Iterating through map and showing table

The first thing I want to say is that I am new to clojure, secondly I want to ask you how to iterate through a map and show all elements in a table? Here is what I have done. This is my map- (def kvote(assoc kvote (keyword kljuc){:id id :liga liga :dan dan :cas cas :domaciTim domaciTim :gostujuciTim gostujuciTim :par par :konacanIshod{:1 jedinica :x nerijeseno :2 dvojka}})) I was using cldwalker table function and did this... (table [ ["liga" "dan" "cas" "id" "par" "1" "X" "2"] [(:liga(ge

Clojure.data.xml: append XML Element

My Goal is to append Child Elements under another XML Element (the parent). Lets say under <Books>. (def bookshelf (xml/element :books {})) So i would like to create <Book> Elements dynamically and append to as Long as they are created one After the other. Does anyone have a clue how to do this using the lib clojure.data.xml? Thx in advance. Horace

Clojure How to load and use native c code in a lein project?

ProblemI'm unable to load and call methods in a compiled c class into a leiningen project. My basic approach is to load a Java class, JavaWrapper.java, that uses JNI to call some native methods in the native code, wrapper.o and then call the methods through this java wrapper class. I imagine there are classLoader issues with loading a java class which loads the native code from a clojure project, but given that I can't seem to directly get clojure code to find the wrapper.o on the library path,

Clojure Riemann email assert failed?

I am using riemann output plugin in logstash and I want to alert using riemann when the user field is root. Logstash-config: if "server2-cronlog" in [tags]{ riemann { riemann_event => [ "service", "My Awesome Logs", "username", "%{user}", "description", "%{command}" ] } } Riemann-config: I add the following lines to the end of riemann config file contents (as we

Clojure: why is sniptest producing LazySeq

I'm creating a template in enlive and having trouble with this snippet which produces lazyseq. When I try this sniptest in REPL it produces "clojure.lang.LazySeq@ba6da9f2". (h/sniptest (template-div) [:div.Row] (h/content (map #(value-cell %) (for [e(:data-content msh-contents)] (vals e))))) The rest of the code needed to test this looks like this (require '[net.cgrand.enlive-html :as h]) (def msh-contents {:title "Events mashup", :data

Clojure looping based on user input

In Clojure I want to create a function that would continually ask the user for an option, execute some code depending on the option, and then quit when the user’s option is “q”. I am comfortable will all of the various Clojure forms that work with sequences, and I could certainly finagle a Java-like solution to the above, but I cannot figure out how to do this in a “clojuresque” manner. Thanks, Jeffrey S

Clojure How eval defrecord generated by defmacro

that's a really weird case! I've reached to a defrecord definition when I call my macro but I only get the code without the evaluation. (defmacro protocol-impl [protocol-definition] ``(defrecord ~(symbol "my-wrapper") [~(symbol "e#")] ~@(let [[type# protocol-functions#] ~protocol-definition] (conj (map (fn [[function-name# function-args#]] `(~function-name# ~function-args# (~function-name# ~(symbol "e#") ~@(next

ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn

I have a function that takes the number of years and salary, then recursively doubles the salary until years is exhausted. However, I keep getting this error: ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn The Code (defn calculate-salary [years salary] (if (= years 0) (salary) (calculate-salary (- years 1) (* salary 2)))) I'm very new to Clojure so I'm sure its something simple, but I just can't seem to figure it out.

Clojure Manage dependencies in `project.clj` from the command line

I would like to search and install clojure dependencies from the commandline. Does there exists a tool/leiningen command/lein change script?/... that can: search for clojure libraries online rewrite project.clj to include the dependency (latest version) update dependencies? Much along the lines of npm install --save (--save-dev) and npm search, for those that are familiar with npm (JS/Node package manager). (Maybe boot provides a more npm-like workflow?)

vector-zip predicate library like data.zip.xml in Clojure?

I've had great success using data.zip.xml but I find I'm in need of same for vector trees. Before undertaking creation of the equivalent of data.zip.xml for vector-zip zippers, I thought it would be good to see if something already exists.

Clojure How does (GET "/" request (str request)) work in compojure

I am wondering what magic is occurring for this code from https://github.com/weavejester/compojure/wiki/Destructuring-Syntax (GET "/" request (str request)) I would expect it to look something like (GET "/" [request] (str request)) Specifically, how is the request bound to the second argument? Is the request always bound to the second argument? What differentiates request vs [request]? I have changed my code to see what happens in each of these scenarios, just trying to understand

Clojure Is order guaranteed when multiple processes are waiting to put data in the same channel?

Here is the code: (ns typedclj.core (:require [clojure.core.async :as a :refer [>! <! >!! <!! go chan buffer close! thread alts! alts!! timeout]]) (:gen-class)) (def mychan (chan)) (go (while true (>! mychan "what is this?"))) (go (loop [i 0] (>! mychan (str "msg" i)) (recur (inc i)))) (go (loop [i 0] (>! mychan (str "reply" i)) (recur (inc i)))) (go (loop [i 0] (>! mychan (str "cur

Clarifying Clojure "Use as" semantics

The effect of (use '[clojure.string :as str]) seems to be loading everything from clojure.string into the current namespace without namespace qualification. The effect of (use '[clojure.string :as str :only (join)]) seems to be loading only join into the current namespace, making the rest of the clojure.string namespace accessible with the str/ prefix. Is there any way to simply make the whole clojure.string namespace accessible with the str/ prefix without selecting any names that I want to dir

Is there a way to create a constrained data type in Clojure?

As an example, a string that contains only a valid email address, as defined by some regex. If a field of this type would be a part of a more complex data structure, or would be used as a function parameter, or used in any other context, the client code would be able to assume the field is a string containing a valid email address. Thus, no checks like "valid?" should be ever necessary, so approach of domaintypes would not work. In Haskell this could be accomplished by a smart constructor (se

How do I get the Dock icon to appear for a Clojure app on a mac?

Currently nothing (not even the java coffee cup) appears. I created my app using lein new reagent name and I've tried these jvm options: java -Xdock:name=Name -Xdock:icon=/Users/bmaddy/Downloads/logo.jpg -Dapple.awt.UIElement=true -Djava.awt.headless=false -jar name.jar

Split vector at max value in Clojure -- better way?

Newbie question: How to split a vector of numbers at and including the first instance of the maximum value in it? So, from this [1 2 3 4 5 4 3 2 1], get [1 2 3 4 5] [4 3 2 1]. The way I'm doing it seems overly complex: (def up5 [1 2 3 4 5 4 3 2 1]) (split-at (inc (.indexOf up5 (apply max up5))) up5) ; => [1 2 3 4 5] [4 3 2 1] Does that seem a little awkward? For example using the defined vector three times. And do we need to use Java to get the index? What would be a better, more idiom

Why there is a "nil" at the end of output in clojure

I am wondering why there is a "nil" at the end of output in clojure. Here is my code: (defn foo [x &argu] (print x &argu)) And the other question is what does "&argu" mean here? An variadic argument or something? Thank you so much!

Clojure How to get logged in user's id from session in LuminusWeb

I've just saved the current logged-in user in session. Now how do I get user's id from session in Selmer templates?. Thanks (defn login-form [{:keys [flash]}] (layout/render "login_form.html" (merge (select-keys flash [:id :pass :errors])))) (defn authenticate [id pass] (when-let [user (db/get-user {:id id})] (when (hashers/check pass (:pass user)) id))) (defn login! [{:keys [params]}] (if-let [id (authenticate (:id params) (:pass params))] ;TODO: Refactor (do &

How to add data to hash set in Clojure?

I have a set of hashmap (or a hashset, an array of hashmaps) like below: (def mydata #{{:rank 2 :page 1 :group "fish"} {:rank 1 :page 1 :group "mammal"} {:rank 3 :page 2 :group "bird"}}) and I have a new hashmap like this: {:group "mammal" :name "lion" :score 566} What I want to do basically is to sort of merge that new hashmap data into the above array, so it would look like this ('group' is the join key): #{{:rank 2 :page 1 :group "fish"} {:rank 1 :page 1 :

Does declare function cause any performance problems in Clojure?

As you know we need to use declare function if we want to use a function without declaring it before so my question is using declare function causes any performance issues? Clojure has single pass compilation so it has to do some kind of tradeoffs over there I assume?

Clojure What does :scope "test" mean in build.boot dependency?

A lot of examples have dependencies written like [org.clojure/tools.nrepl "0.2.12" :scope "test"] I think it means to not include this dependency in prod build, like lein's dev profile, but I can't find any documentation on this. What other scopes are available? Do they have hardcoded meaning within boot or is it something a user can define?

Clojure - Inclusive Range

I am using Clojure to do the following task - Write a function named get-divisors which takes a number n as input and returns the all the numbers between 2 and √

Clojure Extract set of values from collection of maps by specific keys

I'm trying to extract set of values from collection of maps by specific keys. For example, Input: [ {:k1 "v1" :k2 "v2" :k3 "v3"} {:k1 "v4" :k2 "v2"} ] Assuming that getting set of values by :k1, :k2 Desired output: #{"v1" "v2" "v4"} So my solution is (->> [{:k1 "v1" :k2 "v2" :k3 "v3"} {:k1 "v4" :k2 "v2"}] (map #(-> (select-keys % [:k1 :k2]) (vals) (set))) (apply clojure.set/union)) But I wanna know better ways. What do you think?

Clojure zipper to remove all right siblings

I want to write a function for a zipper that removes all right siblings of a node while staying at the same location. (defn remove-all-rights-1 [loc] (if (zip/right loc) (recur (zip/remove (zip/right loc))) loc)) The problem here is that remove returns the location that would have preceded the current node in DFS. Therefore the following example... (-> (clojure.zip/vector-zip [1 [[2] 3]]) (zip/down) (zip/right) (zip/down) (remove-all-rights-1) (zip/replace

clojure macro: unable to resolve symbol

Clojure beginner, trying macros. I'm writing the following macro (defmacro f [exp] (let [[a op b] exp] (list op a b))) (f (1 + 2)) which works as intended. However I tried to replace the returned value from (list op a b) to '(op a b) and I get *unable to resolve symbol op in this context. I figured that the error is caused because list evaluates its arguments first, so I tried with '(~op a b), but still get the same error. What am I understanding wrong?

Clojure design philosophy of functions vs methods

It's often quoted that "It is better to have 100 functions operate on one data structure than 10 functions on 10 data structures." — Alan Perlis and this is something that is heavily observed in Clojure & it's libraries too e.g In the gist here, Rich has explained the design principle of clojure.xml where once the XML file is read, it is converted to a map and then you have all the functions available to manipulate these maps however you need and that you can reuse these functions wit

How does clojure bind variable parameters?

I am a newbie in Clojure.The problem originated when I once checked the source code of conj: (def conj (fn ^:static conj ([] []) ([coll] coll) ([coll x] (clojure.lang.RT/conj coll x));4 ([coll x & xs] ;1 (if xs ;2 (recur (clojure.lang.RT/conj coll x) (first xs) (next xs)) ;3 (clojure.lang.RT/conj coll x))))) The source code of conj shows that it uses recur to implement the function. This source code looks very simpl

Clojure lein repl and any command with "lein" Doesn't Work

I have just started learning Clojure from Daniel Higginbottam's book called Clojure for the Brave and True. Needless to say, you need Leiningen and Cider for a good Clojure workflow. Before I have tried installing cider to emacs, my Leiningen was working fine but somehow after I have tingled some settings with emacs (installing cider), my Leiningen installation started to give stack trace errors such as below: (I don't know how can this happen at all) How can I fix this? (Also, I have tried re-i

Creating a lexer in Clojure

If I want to pass a string in a function and return the token type of the string typed using Clojure, such as "int x=5;" will be ":alpha :alpha :alpha :whitespace :equal :digit". How will I write the lexer function in Clojure?

Clojure Why are these `select` elements not being rendered?

I'm working on a project for a client where there needs to be 125 dropdown menus displayed on one page. I of course am not going to manually add all those so I wrote a simple for expression to do it for me. This works for the vast majority of the dropdown menus (which are just select tags), but some do not show up at all. And it is the same three each and every time. Why are these same three never being rendered? When looking in the Elements view in Chrome Dev Tools, it shows the dropdowns as be

Executing Functions Inside of Clojure String?

I'm working on a static site generator project and at one point I get a string representation of the site (in hiccup format) that I can manipulate. I convert that string to a map: (clojure.edn/read-string page) At which point I'll have my page as something like: { :header { :title "Index" :meta-desc "Indx Page"} :page [:div.Page.Home !!+Do-Math+!! ; This is the core of the question [:p (do-math 2 2)] ; This is also an option to rep

  1    2   3   4   5   6  ... 下一页 最后一页 共 54 页