Lets say I have a generator for interval structs e.g.
(struct interval (lo hi)
#:methods gen:custom-write
[(define write-proc
(make-constructor-style-printer
(lambda (obj) 'interval)
(lambda (obj) (list (interval-hi obj) (interval-lo obj)))))])
(define (choose-interval [min-value -100] [max-value 100])
(bind-generators
([lo (choose-real min-value max-value)]
[hi (choose-real lo max-value)])
(interval lo hi)))
According to the docs generator has a member called proc that takes a test size argument and a random number generator. But where do I get this random number generator? The make-random-generator symbol in the docs is not actually exported by the module!
How do i get some values out of this generator so I can be sure it is working correctly?
make-random-generator should be exported. See This PR.
Related
Question Asked
(defun a-sum(n p)
(setq sum 0)
( loop for i from n to p
do(setq sum (+ sum i))
)
(format t "~d" sum)
)
My code works for all of my Test Cases but using the loop method I keep returning a NIL right before my value. Is there any way to stop this? Or maybe an alernative method I'm meant to use when faced with a probem like this?
Here is your code formatted in a readable way, please refer to https://stackoverflow.com/help/formatting when asking question and follow the conventional ways of formatting the programming language your question is about:
(defun a-sum (n p)
(setq sum 0)
(loop for i from n to p
do (setq sum (+ sum i)))
(format t "~d" sum))
There are some problems here, notably:
you call SETQ on symbol sum, but there is no variable in scope that is declared with such a name. You introduce variables with let, for example:
(let ((sum 0))
;; here you are allowed to use SETQ
(setq sum 1))
Strictly speaking, your code is not a conforming program for Lisp, but it still works: the call to SETQ does modify the symbol-value of sum, so that's as-if you used a global variable. This is usually not a good idea since then your functions have effects that are not localized to their body, but also change the environment.
In a function body, the last expression is the value returned by the function, so here the value being returned is the result of evaluating (format ...). In the case you format to a stream, which is the case here, the return value is always NIL. That's why you have a NIL result. If you want to return sum then you need to have sum as the last expression in your function.
Generally speaking, a function should do one thing, not mix different actions together: either you compute a sum, or you print it, but try not doing both at the same time (except when debugging).
The loop construct is powerful enough to do the job with needing to use an intermediate sum, calling do (setq ...), etc. Read LOOP for black belts and you should be able to rewrite it more concisely.
The sum of consecutive numbers is a well-known formula that admits a solution without loops.
I have been resisting giving an answer, because instructors should not ask students questions like this (see below).
The question is to write a function which computes the sum of i from n to p, where n and p are integers, n and p >= 0 and p >= n (the question does not state this latter requirement, and it's easy to relax it in the answer, but let's assume it).
Well, before you write some laborious and futile loop, think a bit. Write out the sum by hand:
s = n + n+1 + ... + p
= (n + n+1 + ... + p
+ p + p-1 + ... + n)/2
= (n+p + n+p + ... + n+p)/2
And now there are (p - n + 1) terms in this sum, all of which are n+p. So
s = (p - n + 1)*(n+p)/2
Or
(defun a-sum (n p)
(/ (* (+ (- p n) 1)
(+ n p))
2))
And here's why you do this:
> (time (a-sum/mindless 0 1000000000))
Evaluation took:
6.716 seconds of real time
6.716005 seconds of total run time (6.713082 user, 0.002923 system)
100.00% CPU
0 bytes consed
500000000500000000
> (time (a-sum 0 1000000000))
Evaluation took:
0.000 seconds of real time
0.000003 seconds of total run time (0.000002 user, 0.000001 system)
100.00% CPU
0 bytes consed
500000000500000000
So here's the thing: if you are the instructor and you're reading this (which I am sure you are, because I would be) don't ask questions which have well-known closed-form solutions and expect students to write the terrible brute-force solution, because doing that is teaching people to be bad programmers, and you should not do that.
I am new to Racket Lang and previously I wrote thousands of lines of code in C++, Java and C. I am trying to figure out how to do the following task:
Given an array (like C uint8_t array) with the following format:
First byte is used to indicate the "format", let's say this could be 0x0a, 0x0b and so on.
Remaining data may include C strings without the null terminator and integers.
Write a function that parses the array and puts the values in some variables.
Before asking here, I was reading: https://docs.racket-lang.org/guide and also https://docs.racket-lang.org/reference
My approach is as follows:
I am using a byte string because it seems it can be used to mimic the C++/C arrays.
I am using tail recursion to traverse the "array".
Questions:
1) In C, I always use the return value of a function as an error code: 0 is ok and any negative value is an error. With Racket, I am using multiple return values to indicate: a) the return code, b) the processed value(s), i.e. something like:
(values return_code out1 out2 ...)
What do you think? Do you recommend the use of exceptions for error handling?
2) What's the best approach to process arrays in Racket? I mean, the best according to the offered by Racket and to achieve a good performance.
Thanks!
Edit1:
Regarding my first question (the return codes), I am calling many functions and I would like to return an exit code that helps me to know if there was an error inside the function. This is a sample code:
#lang racket
(define (is_valid in)
(cond
[(and (>= in 10) (<= in 15)) #t]
[else #f]))
(define (copy_values in)
(define len (bytes-ref in 2))
; 3 is where the string "ABCD" begins
(define str (subbytes in 3 (+ 3 len)))
(define numbers (subbytes in (+ 3 len)))
(values str numbers))
(define (parse in)
(define type (bytes-ref in 0))
(if (is_valid type)
(let ()
(define-values (str numbers) (copy_values in))
(values #t str numbers))
(values #f 0 0)))
; format: type strlen
; len |-- str --| | -- numbers -- |
;
(define input1 (bytes 10 10 4 65 66 67 68 110 120 130 140 150))
(define input2 (bytes 1 10 4 65 66 67 68 110 120 130 140 150))
(parse input1)
(parse input2)
This is the output in DrRacket:
Welcome to DrRacket, version 6.7 [3m].
Language: racket, with debugging; memory limit: 128 MB.
#t
#"ABCD"
#"nx\202\214\226"
#f
0
0
Look how I use the (values ...) stuff, does that make sense?
To return a value to the operating system, use (exit [v]).. Other values should probably go to standard out and/or standard error. This means writing them before the program exits.
In terms of assigning the values of an array to variables, there are many ways to do it depending on how lexical scope comes into play within the function and module and across modules. Also reference semantics versus value semantics are considerations.
Finally, there is no compelling reason to choose recursion over an explicit loop when dealing with a byte-string. bytes-length is a low level primitive implemented in C and will return the length needed for a loop without testing for an empty byte-string.
I have the following structures:
(defstruct track
size
env
startpos
endpositions)
(defstruct state
pos
vel
action
cost
track
other)
I have a state and Im trying to access endpositions(list of lists)
(setq coluna_final (nth 1 (nth 0 (state-track-endpositions st))))
but I get the error: EVAL: undefined function STATE-TRACK-ENDPOSITIONS
What am I doing wrong?
The first defstruct defines (inter alia) function track-endpositions, and the second defines state-track. Lisp has no way to know that the latter returns a track (even if you declare the slot type, it will not define the function you want).
You can do it yourself:
(defun state-track-endpositions (st)
(track-endpositions (state-track st)))
I want to create a lisp function which corresponds to a macro in C.
e.g., there is one HIWORD in win32 API, which is defined as a macro in the header file.
I tried to define it as below but was told that HIWORD is unresolved.
CL-USER 4 > (hiword #xFFFFFFFF)
Error: Foreign function HIWORD trying to call to unresolved external function "HIWORDW".
I just want to know how to create a wrapper for C macros like for C functions.
(fli:define-c-typedef DWORD (:unsigned :long))
(fli:define-c-typedef WORD (:unsigned :short))
(fli:define-foreign-function
(HIWORD "HIWORD" :dbcs)
((dwVal dword))
:result-type word :calling-convention :stdcall)
You cannot do this directly. C preprocessor macros are not preserved in the compilation process, i.e., there is simply no artifact in the generated object files, which would correspond to the C macro itself (though its expansion may be part of the object file multiple times). And since there is no artifact, there is nothing to bind to with FFI.
You can, however, provide a wrapper function
#define HIGHWORD(x) /* whatever */
int
highword_wrapper(int x)
{
return HIGHWORD(x);
}
and this one can be used with FFI.
No need to jump into another language. Shifting and masking in Lisp:
(defun hiword (val)
(logand (ash val -16) #xFFFF)
(defun loword (val) ;; ditto
(logand val #xFFFF))
Another way: using the ldb accessor with ranges expressed using byte syntax:
(defun hiword (val)
(ldb (byte 16 16) val) ;; get 16-bit-wide "byte" starting at bit 16.
(defun loword (val)
(ldb (byte 16 0) val) ;; get 16-bit-wide "byte" at position 0.
I am currently developing a small CMS using the wonderful Enlive as templating engine. Enlive has a macro called at that takes a node (a map) specifying the HTML snippet and an arbitrary number of tuples each consisting of a selector (a vector) and a transformation (a closure).
(at a-node
[:a :selector] a-transformation
[:another :selector] another-transformation
...)
Now I want to generate the tuples depending upon incoming data/context. I have tried a lot of different things without success. For example
(let [this (repository/u "http://example.com/ACMECorp")
statements (repository/find-by-subject this)
context {:depth 1}]
`(at (snippet-for 'this 'context)
[root] (set-attr :about (str 'this))
~#(loop [rules []
st statements]
(if-not (seq st)
rules
(recur (conj rules
`[:> (attr= :property ~(str (repository/predicate (first st))))]
`(content (renderit ~(repository/object (first st)) 'context)))
(rest st))))))
Any help is highly appreciated.
-Jochen
Clojure is a Lisp, so you can always fallback to building the code you'd want as a list, and call eval on it. I'm not 100% sure about the code you gave, but I'd guess you just want to enclose your whole syntax-quote in an eval call.
(let [this (repository/u "http://example.com/ACMECorp")
statements (repository/find-by-subject this)
context {:depth 1}]
(eval `(at (snippet-for 'this 'context)
[root] (set-attr :about (str 'this))
~#(loop [rules []
st statements]
(if-not (seq st)
rules
(recur (conj rules
`[:> (attr= :property ~(str (repository/predicate (first st))))]
`(content (renderit ~(repository/object (first st)) 'context)))
(rest st)))))))
Not sure if they are interchangeable, but take a look at the at* function. Seems to me that your problem is at being a macro.
EDIT: They're not. Call it like this:
(at* a-node
[[:a :selector] a-transformation
[:another :selector] another-transformation
...])