clojure,scheme,lisp,common-lisp , No-argument (and) returns t

No-argument (and) returns t


Tag: clojure,scheme,lisp,common-lisp

Both CL and Scheme define (and) to return t (or #t) with no arguments.

I'm trying to understand the rationale for this. My naive assumption is that an empty set is false, and passing in zero arguments feels like passing in nothing that can be true.

Edit: clojure follows the same convention. I must be missing some basic Lisp assumption.


The empty product is 1. The reason is that 1 is a neutral element for *.

If you have the product of 2 and 3 and then multiply by the product of nothing, you will get 2*3*1 = 6. We can write

  (product (product 2 3) (product)) 
= (product 6 1) 
= 6

The same computation with and:

  (and (and #t #t) (and)) 
= (and #t ?) 
= #t

We want the empty (and) to give a value ? that doesn't affect the result. The answer is #t since #t is a neutral element.

(and x #t) = x   for all boolean x


Querying the number of elements in a buffered core.async/chan

Having a buffered chan, say (def c (clojure.core.async/chan 100)) is it possible to query how many elements are currently inside the chan?...

What does clojure 'val' return this value?

I'm just starting to learn clojure and have been reading some simple examples and then doing my best to rtfm for concepts. However I'm a bit confused by what val is doing in the example below. This has been taken from the Clojure doc examples for val. (first {:one :two})...

Build macro result with loops

I'm building a macro that should be called like this: (myMacro MyController something otherthing (defn onFoo [this event] (println "ok")) (defn onBar [this event] (println "ok")) ) After the first three parameters I want to be able to pass a few functions that should be used to build the function...

clojure performance on badly performing code

I have completed this problem on hackerrank and my solution passes most test cases but it is not fast enough for 4 out of the 11 test cases. My solution looks like this: (ns scratch.core (require [clojure.string :as str :only (split-lines join split)])) (defn ascii [char] (int (.charAt (str char)...

Is there a way to see the body of a lambda in Racket?

Say I have this code: #lang racket (define a ((λ (x) x) ((λ (y) y) (λ (z) ((λ (w) w) z))))) I know intuitively that this lambda expression is (extensionally) equal to (λ (z) z) My question is if there is a way to print out the body of a...

How can I use single or double quote in Clojure Macro?

I am making a macro which uses single quotes. However, whenever I parse the macro the single quote text like: 'java' :is expanded to: (quote java') Does anyone know a way around this so that it doesn't expand to the quoted form? Update I have a kind of working workaround...

Clojure throws an exception when I don't expect it to

I have this code to get data from sumo logic and other services. core.clj has this, which parses the arguments and routes it to the right function in route.clj (def cli-options [ ["-a" "--app APPNAME" "set app. app can be: sumologic or jira"] ["-?" "--help"] ]) (defn -main [& args]...

Brand new Luminus app giving Error: Could not find or load main class clojure.main

I just created a Luminus app by running: lein new luminus foobar and when I try to run it with foreman like this: foreman start the way the docs describe, I get this error: Error: Could not find or load main class clojure.main which is also the same error I...

clojure - take-while to include last item when predicate is false

I have the following function that uses take-while (defn process [[cash amount wrappers]] (let [bought (int (Math/floor (/ cash amount))) free (->> (iterate (partial unwrapper wrappers) bought) (take-while (partial (fn [w a] (prn (str "a = " a)) (>= a w) ) wrappers)))] The problem I have is that I...

AngularJS $http GET method to backend server: Request Method:OPTIONS 405

$http GET request to a clojure backend, to get a list of services. I get is an OPTIONS request (???), which gets a 405 response... <code> var config = {headers: { 'Authorization': 'Bearer d2VudHdvYW5nZV9tZQ', "X-Testing" : "testing" } }; $http.get(SERVER.MESSAGE_SERVICES, config) .success(function(successCallback) { $ = successCallback; }) .error(function(errorCallback) { console.log(errorCallback.toString);...

Clojure: Idiomatic/clean way to avoid NPE in a monad-like way

I'm a little chagrinned that some of the built-in Clojure functions have what seems to me to be an inconsistent behavior. I'm trying to do this: (let [kwns (namespace (keyword v))] ...) in a context where v might be nil. The keyword function works as I'd expect (returns nil), but...

Is there a formal way of proposing/discussing changes to Clojure?

Is there a formal way of proposing/discussing changes to Clojure?

clojure quoting inside let

Quoting (both syntax and non-syntax) seems to fail to detect vars inside a let statement: (let [foo 1] (eval `(print foo))) This will generate an error or use whatever prior value bound was bound to foo in (def foo bar). Is there a way to make the syntax quote use...

Clojure: difference between applying directly or by way of a function

The aim is to play with a slight modification of the Caesar cipher. First a function to move a character: (defn move-char [c shift idx encode-or-decode] (let [ch (int c) val (mod (* encode-or-decode (+ shift idx)) 26)] (cond (and (>= ch (int \A)) (<= ch (int \Z))) (char (+...

Questions about Vars Clojure

I'm new in Clojure and i read that it is a functional language. It says that Clojure doesn't have variables, still when i find (def n 5), what's the difference between it and a variable? I can change the value of the var after, so is it really that different...

Why such implementation of partial in clojure.core

I stumbled across implementation of partial function in cojure.core. It looks like this: (defn partial "Takes a function f and fewer than the normal arguments to f, and returns a fn that takes a variable number of additional args. When called, the returned function calls f with args + additional...

Using MIT/GNU Scheme

I have downloaded the MIT/GNU Scheme implementation of LISP in order to understand Structure and Interpretation of Computer Programs. However, I am a bit confused about what I am dealing with when I launch the program. When the program is launched, I get two windows: the "MIT/GNU Scheme" window, and...

Clojure loop receiving IllegalArgumentException Key must be integer clojure.lang.APersistentVector.invoke

I'm stuck trying to get a simple loop in Clojure to work and I don't know how to proceed to get rid of the exception. I'm trying to write an arrange function to exchange items in a vector. Here is the code. (defn exchange [v i] (let [[src dst] i]...

How to specify max memory for clojure heroku app?

Running a clojure app on Heroku, I've specified this in my leiningen profiles.clj :jvm-opts ^:replace ["-Xms128m" "-Xmx350m" "-Xss512k" "-XX:MaxMetaspaceSize=150m"] And I'm running my worker with lein trampoline run But, I get these errors currently: 2015-06-20T14:38:14.652680+00:00 heroku[worker.1]: Error R14 (Memory quota exceeded) 2015-06-20T14:38:34.779145+00:00 heroku[worker.1]: Process running mem=552M(107.8%) 2015-06-20T14:38:34.779145+00:00 heroku[worker.1]: Error R14...

Clojure invokeLater null pointer

This code: (import 'javax.swing.SwingUtilities) (SwingUtilities/invokeLater (print "hi")) Causes this error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at java.awt.event.InvocationEvent.dispatch( ... I don't know if this is a problem, since the code itself actually works (printing to the REPL) despite the error. However, modifying swing components does not seem to work properly: a...

Append to clojure vector from within loop

I have: (defn keep? (def sum []) (loop [i 0] (when (< i 10) (conj sum 10) (recur (inc i)))) sum ) This just gives me and empty vector even though I am conj-ing 10 onto sum. Is this because it is not in-scope within the Loop? How would I...

Loop in clojure with or condition

I'm trying to write a function in clojure that calls a condition for each value in a vector; the function should return the OR of the result of the condition applied to each value. Eg I have a vector [1 2 3 4] and a condition (>= x 3) where...

Clojure avoid repetition on tests

In my tests I need repeat this a block of tests for each function. In this case I'm testing bad-request function, the things that need change between each test is the bad-request call, code, and error. (deftest t-bad-request ... (testing "with data" (equal (merge error code message DATA) (bad-request MESSAGE...

Accessing argument's metadata in Clojure macro

Is there a way to retrieve the metadata of the arguments inside a clojure macro without using eval? The only thing I could come up with so far is this: (def ^{:a :b} my-var) (defmacro my-macro [s] (prn (eval `(meta (var ~s))))) (my-macro my-var) ;; Prints {:a :b, :name my-var,...

Datomic and HornetQException “unable to validate user”

I'm trying to connect to Datomic "dev" running on a separate host, but get the following error: "Error communicating with HOST (some-IP-address) on PORT (some-port-number) ...." Then further down the stack trace: Caused by: HornetQException[errorType=SECURITY_EXCEPTION ... Unable to validate user: (some-string) This is with "Seattle" sample schema that comes with...

How can I create a global object, and attach a string and a function to that object, in ClojureScript?

How can I create a global object, attached to the window, and attach a string and a function to that object, in ClojureScript? For example, an myobject that looks like: {"foo": function () {..}, "bar": "somestring"} => function () { .. } => "somestring"...

Clojure: wrap-ssl-redirect on heroku?

I've just tried add this wrapper (-> routes (wrap-ssl-redirect)) for auto redirecting http to https, but when I deploy to heroku, the https:// doesn't get green in my browser, and the website doesn't load. Isn't the default heroku port 443, which should also be the default from wrap-ssl-redirectfunction? What is...

Does the Zookeeper Watches system have a bug, or is this a limitation of the CAP theorem?

The Zookeeper Watches documentation states: "A client will see a watch event for a znode it is watching before seeing the new data that corresponds to that znode." Furthermore, "Because watches are one time triggers and there is latency between getting the event and sending a new request to get...

Why does ^metadata 'symbol not work?

The documentation on metadata claims that ^{:hi 10} 'x is equivalent to (with-meta 'x {:hi 10}), but I can't see that. Evaluating the following on a repl, (binding [*print-meta* true] (prn ^{:hi 10} 'x) (prn (with-meta 'x {:hi 10}))) prints the following, which shows that the first case doesn't get...

Clojure interop with Java: how to call a class?

I have a Java app that has a class at this address, inside a standard Maven layout: src/main/java/com/ollio/nlp/ The class and method that I want looks like this: package com.ollio.nlp; public class Transformer { public String transform(String JSONInput) { I store the jar artifact locally in my Clojure app at...

ImageIO import not working Clojure

I'm a bit of a Clojure novice, but I don't understand what's wrong about my code. The code bellow to my knowledge should set imgto a new BufferedImage object. (import javax.imageio.ImageIO) (import (def img (ImageIO/read (File. "C:\\input.png"))) However, when I execute lein run I get this exception: Exception in...

What is clojure.core equivalent of lodash _.pluck

Lodash _.pluck does this var users = [ { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 } ]; _.pluck(users, 'user'); // → ['barney', 'fred'] Good thing about it is it can also go deep like this: var users = [ { 'user': {name: 'barney'}, 'age': 36 },...

ePassport Problems reagrding MAC creation in ICAO 9303 “worked examples” in Java/Clojure

i work on a application where I need to read Data from epassports. I'm working through the "worked examples" in ICAO Doc 9303 Part 3 Volume 2 (Third Edition). There is a section in the worked examples, where they put together the MUTAUAL_AUTHENTICATE apdu. It involves calculating the MAC of...

Apply a sequence of functions to data

I wish apply a sequence of functions to a data, like pipe: I know it has ->>and ->, also I have difficulty in defining the internal functions (defn create ([code error] {:statusCode code :error error}) ([code error & [message data]] (create code error) - I want pipe it result...

Immutant2 server logs showing fishy error message

I got this error message a couple of times 21:36:01,172 ERROR [io.undertow.request] (default task-18) Undertow request failed HttpServerExchange{ CONNECT}: java.lang.IllegalArgumentException: UT000068: Servlet path match failed at io.undertow.servlet.handlers.ServletPathMatchesData.getServletHandlerByPath( at io.undertow.servlet.handlers.ServletPathMatches.getServletHandlerByPath( at...

How is it possible to filter a list of directories via “directory-exists?”?

I recently discovered a strange behaviour of racket: Whenever I try to filter a list of directories created via directory-list my REPL returns me an empty list, but when I try the same with an quasiquoted list my REPL returns a correctly filtered list. My questions is now: Why it's...

How to perform synchronous parallel functions in Clojure?

I have an application which has an initial flow that can be done in parallel: Fetch two JSON documents (I use clj-http for that) Parse these documents (extract only required data) Join the results Dump them into a one file So there's something like that: some-entry-point /\ / \ /...

Racket\Scheme compare and delete unwanted items in a list

I have 2 lists: (Define list1 '("xx1" "xx2" xx3" "xx4" "xx5")) (Define list2 '("xx2" "xx4" "xx5")) the items in the list above are just an example, but either way it will be a string item. What I need to do is compare both lists and remove the items in list1...

Group vectors with same first element into lists of vectors

I have ([AA moo foo boo][AA soo doo foo][BB woo roo too][BB koo ooo yoo]) I need to group it so I get lists of vectors with the same first element: ([AA moo foo boo][AA soo doo foo])([BB woo roo too][BB koo ooo yoo]) Is there a grouping function? Thanks...

clojure and ctags, catching def* forms

So I found the following snippet from a Gist a while back: --langdef=Clojure --langmap=Clojure:.clj --langmap=Clojure:+.cljx --langmap=Clojure:+.cljs --regex-clojure=/\([ \t]*create-ns[ \t]+([-[:alnum:]*+!_:\/.?]+)/\1/n,namespace/ --regex-clojure=/\([ \t]*def[ \t]+([-[:alnum:]*+!_:\/.?]+)/\1/d,definition/ --regex-clojure=/\([ \t]*defn-?[ \t]+([-[:alnum:]*+!_:\/.?]+)/\1/f,function/ --regex-clojure=/\([ \t]*defmacro[ \t]+([-[:alnum:]*+!_:\/.?]+)/\1/m,macro/ --regex-clojure=/\([ \t]*definline[...

Accessing call stack depth in Scheme

In order to demonstrate the effectiveness of tail recursion, I would like a way to access the depth of the call stack dynamically in Scheme. Is there a way to do this? If not, is there a way to do this in other major functional languages (OCaml, Haskell, etc.)?...

Leiningen REPL not autoloading project.core namespace [duplicate]

This question already has an answer here: how to load ns by default when starting repl 2 answers I'm new to Clojure so this could very well be an easy question. I'm having an issue with the REPL while using Leiningen. Previously, I had created an app project while...

Sequentially calling a function with elements from a vector

Suppose I have a function f that accepts two arguments x & y. I also have a vector X composed of elements x1, x2, ... xn. How can I write a function g, where g(X, y) calls f(xi, y) for all x? Further specification: I would like g to return...

Clojure - apply to all but nth element

I have a vector that looks like: [ "1" "2" "3" "4" ] I wish to write a function returns the vector to: [ 1 "2" 3 4 ] ; Note that the second element is still a string Note that nothing is changed, an entirely new vector is returned....

Simple runscript example with jclouds and clojure (or even just jclouds)

I have this clojure code (let [group-name "my-test-group" compute (compute-service provider user password) node (create-node compute group-name) node-id (.getId node)] (.runScriptOnNode compute node-id ??) (destroy-node compute node-id)) and I would like to run ls on my instance just as an example. What do I put in the ?? to make...

More readable messages with :pre and :post?

In clojure I am using :pre like this user=> (defn cannot-take-empty [x] {:pre [((complement empty?) x)]} 1) #'user/cannot-take-empty user=> (cannot-take-empty #{}) AssertionError Assert failed: ((complement empty?) x) user/cannot-take-empty (NO_SOURCE_FILE:186) That's great, but it doesn't explain the business reason why it doesn't make sense to pass in an empty collection. (Or...

Why is my streamparse topology definition complaining about a wrong number of arguments to thrift$mk-topology?

I'm trying to get a very simple streamparse (i.e. Apache Storm) spout working, but I'm getting the error below when running sparse run -t 120: Caught exception: Wrong number of args (1) passed to: thrift$mk-topology clojure.lang.ArityException: Wrong number of args (1) passed to: thrift$mk-topology at clojure.lang.AFn.throwArity ( clojure.lang.AFn.invoke ( clojure.lang.AFn.applyToHelper...

in clojure, function argument type mismatch

clojure, function argument is vector, but it takes a map without problem. (defn flower-colors [colors] (str "The flowers are " (:flower1 colors) " and " (:flower2 colors))) (flower-colors {:flower1 "red" :flower2 "blue"}) ;; -> "The flowers are red and blue" Function flower-colors suppose to take vector type argument, but with...

deploy compojure app that is also a CLI app

I have a Clojure app that I can use both from the command-line, and as a Compojure app. I did that by putting a ring handler and a main function ( in my leiningen project.clj. {... :main my-app.core :ring {:handler my-app.handler/handler }} The handler is defined (defroutes handler ...). Now...

How to require dependencies in Clojure?

I have two questions regarding dependencies in Clojure project. Is there something like :dev-dependencies or :test-dependencies so that I don't have to download them all on lein run? So until I run my tests I don't need to have these extra libraries. Can I load dependencies in one file and...