clojure,macros,eval , clojure quoting inside let

clojure quoting inside let


Tag: clojure,macros,eval

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 the "local" variables that let defined instead?



You were close, this should do the work (basically, you should unquote the local var in the quoted statement)

(let [foo 1] (eval `(print ~foo)))

Also, while eval is certainly a valid language function, what is the overall goal? There may be better ways altogether.



Append the string provided by __FUNCTION__ macro

I have defined a macro as following: #define ADD_TIME_ENTRY(_name_) m_pTimeMeasurement->addTimeEntry(_name_); Now, I want to pass the function name through ADD_TIME_ENTRY() in whichsoever function I put ADD_TIME_ENTRY() ADD_TIME_ENTRY(__FUNCTION__) works fine for me but now, I want to add "_start" or "_stop" at the end of the function name. I mean, I...

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

Unexpected output printf statement [duplicate]

This question already has an answer here: Why is “i” variable getting incremented twice in my program? 8 answers Why outputs of i and j in the following two printf()s are different? #include <cstdio> #define MAX(x,y) (x)>(y)?(x):(y) int main() { int i=10,j=5,k=0; k==MAX(i++,++j); printf("%d %d %d\n",i,j,k); i=10,j=5,k=0; k=MAX(i++,++j); printf("%d...

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

Understanding NASM Macro

I've come around this macro in a assembly source file and I just can't figure out how it's working. So first I come around this function (hevc_deblock.h): cglobal hevc_v_loop_filter_chroma_8, 3, 5, 7, pix, stride, tc, pix0, r3stride sub pixq, 2 lea r3strideq, [3*strideq] mov pix0q, pixq add pixq, r3strideq TRANSPOSE4x8B_LOAD...

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

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

create a macro in sas

I have a report that is generated once a year. each report has the form of the year inside the name - report-2011.xls, report-2012.xls etc. each report contains the following vars: ID, SAL=average monthly salary of that year, Gender (0=male, 1=female), Married (0=not married, 1=married), I need to create a...

How does this code print odd and even?

#define MACRO(num, str) {\ printf("%d", num);\ printf(" is");\ printf(" %s number", str);\ printf("\n");\ } int main(void) { int num; printf("Enter a number: "); scanf("%d", &num); if (num & 1) { MACRO(num, "Odd"); } else { MACRO(num, "Even"); } return 0; } Please explain the above code (if/else condition and how...

Extract Argument from C Macro

I have a number of definitions consisting of two comma-separated expressions, like this: #define PIN_ALARM GPIOC,14 I want to pass the second expression of those definitions (14 in the case above) to unary macros like the following: #define _PIN_MODE_OUTPUT(n) (1U << ((n) * 2U)) How can I extract the second...

C++ / C #define macro calculation

Suppose I have #define DETUNE1 sqrt(7)-sqrt(5) #define DETUNE2 sqrt(11)-sqrt(7) And I call these multiple times in my program. Are DETUNE1 and DETUNE2 calculated every time it is called? Thanks. Please don't downvote this, I really want to know and a search didn't turn up anything definite. ...

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

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

Macro to push arguments onto stack

I've been working on a fun little project to mess around with how functions are called and I need a macro to push arguments as it'll be quite time consuming to push the arguments manually for every instance of this obfuscated call. This is my code so far: #define pushargs(...)...

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

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

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

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

Use Weka from ImageJ macro: 'path' is required but unset

I have tried Calling Weka from an ImageJ(Fiji) macro: run("Trainable Weka Segmentation", "open=C:\\input\\test.tif inputfile=C:\input\test.tif path=[Ljava.lang.String;@77e655d8"); But when I run that I get an error message: 'path' is required but unset This line is exactly the line I get when recording a macro and opening test.tif when the Trainable Weka Segmentation...

Why is my C code printing out an extra line of rows?

#include <stdio.h> #define rows 500 //can define rows as any number int main() { int i,j; for(i=0;i<=rows;++i) { for(j=0;j<(2*i+1);++j) { printf("* "); } printf("\n"); } return 0; } So here is my code, what it does is it prints the number of rows set by #define and creates a right...

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

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

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

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

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

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

Can I create a macro that unrolls loops?

I'm trying to write some fast matrix code in Rust and to do this needs to ensure that loops are unrolled. Is there a way to create a compile-time for-loop? E.g: I want unroll_loop!(f, a, 3); to generate f(a, 0); f(a, 1); f(a, 2); ...

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

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

Combining multiple template classes to one class using typedef

I have the following piece of code. Let us have the function declaration and implementation seperate. #include <iostream> class Y1 {}; class Y2 {}; template <class T1, class T2> class A { public: explicit A(); void foo() const; int bar() const; }; template <class T1, class T2> A<T1, T2>::A() {}...

how to apply macro on list of lines with vim

let's suppose I want to apply a macro stored on register 1 on lines: 2, 5, 9 but without applying on lines in between. I saw that you can give a range but that is not what I want. I've tried some variation on :2, 5, 9 @1 without success

Read input into string in Lisp reader macro

I am trying to make a reader macro that would convert @this into "this". This is what I currently have: (defun string-reader (stream char) (declare (ignore char)) (format nil "\"~a\"" (read-line stream t nil t)) ) (set-macro-character #\@ #'string-reader ) The problem is that this requires that I put a...

How to control C Macro Precedence

#define VAL1CHK 20 #define NUM 1 #define JOIN(A,B,C) A##B##C int x = JOIN(VAL,NUM,CHK); With above code my expectation was int x = 20; But i get compilation error as macro expands to int x = VALNUMCHK; // Which is undefined How to make it so that NUM is replaced first...

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

Can I create a macro or shortuct for a step of XPath in XQuery?

Do we have Macros in XQuery? If yes, could you please give an example of their usage. I have the following code let $x := //price/ancestor::* Can I someway, using macros or other things write it as follows: let $x := //price/outward So, the outward should mean ancestor::*...

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

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

Why don't I get a warning when I declare a variable with same name in a macro that already exists in a function?

Playing with a macro and thought about the following scenario. Declaring variable in a macro which already exists in function from which this macro has been called, why compiler doesn't complain. When I declare in a code a variable it give me a warning: Redefinition of 'temp' I think that...

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 },...

Creating a function in compile time using a bitmap like macro

I have an ansi C function to sum up values from an array, based on patterns. Something like: long sum_all_according_to_pattern(int n, int *values, int *pattern) { long sum = 0; int i = 0; for(;i<n;i++){ if(pattern[i]) sum+=values[i]; } return sum; } Let's say I've a set of patterns such as:...

Why do I have to expose a macro implementation's 'use' in the client library?

I'm trying to use a macro I've created in a separate module. With reference to this SO question, I've imported a macro fine. However it seems that I have Update to add macro implementation #![macro_use] use std::fmt; use std::ffi::CString; use std::ffi::CStr; use std::str; extern crate libc; pub enum DbaxError...

How to share same header files between kernel modules and userspace applications.

I want to implement a simple module in which an ioctl() method is used. In the kernel module, I use kernel macros, such as _IO(), _IOWR(), etc., to define my own ioctl sub-commands. In facts, I don't care the actual values of these definitions for that I will always use...

How to test whether an identifier that is accessible only through a #define macro is defined?

I have a #define mapping an identifier (a function name) to a new name like this: #define A doStuff This part I cannot do anything about, I have to access "A" since the actual identifier (doStuff here) may change (and this is not under my control). Now the referenced symbol...

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

Split string in macro

I've a class name with its namespace, like BasicType::MyType. It's possible to create a macro that split the name and uses only the part after the scope operator (I want to create a MyType object in macro without the first part)? EDIT: I'm using a library with different classes in...

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

defining recursive values C

#define BLOCK_OFFSET(block) (BASE_OFFSET+(block-1)*block_size) usage lseek(fd, BLOCK_OFFSET(group->bg_inode_table)+(inode_no-1)*sizeof(struct ext2_inode),SEEK_SET); This is a fragment of a code im trying to understand and I have no idea how that definition works. Is it recursive? Can someone explain step by step whats happening in that lseek?...

Providing new version of existing macro with parameters

We have an existing log macro in our code. Lets call it LOG_XXX where XXX is the log level to use, such as LOG_INFO, LOG_DEBUG, LOG_ERROR etc. We stream log messages to the macro: LOG_INFO << "This is a log message."; Under the covers, the macro creates a temporary object...