(Random) in Common Lisp Not So Random? - random

Okay, final question and I'll have finished my number guessing game in Common Lisp! :D Whenever the game starts (or a new game begins after the first game), the following function is called.
;;; Play the game
(defun play ()
;; If it's their first time playing this session,
;; make sure to greet the user.
(unless (> *number-of-guesses* 0)
(welcome-user))
;; Reset their remaining guesses
(setq *number-of-guesses* 0)
;; Set the target value
(setq *target*
;; Random can return float values,
;; so we must round the result to get
;; an integer value.
(round
;; Add one to the result, because
;; (random 100) yields a number between
;; 0 and 99, whereas we want a number
;; from 1 to 100 inclusive.
(+ (random 100) 1)))
(if (eql (prompt-for-guess) t)
(play)
(quit)))
So supposedly, each time the player starts a game, *target* should be set to a new random integer between 1-100. However, each time, *target* defaults to 82. How do I make (random) act... randomly?

You need to seed the random state at the start of the program.
(setf *random-state* (make-random-state t))
;; # this initializes the global random state by
;; "some means" (e.g. current time.)

I think that if you define a function with a random number in it, it is not called when you call the function, actually, it will be determined when you load in the file and when it runs this definition it is fixed to that value. Then you are calling the function each time, the number will always be the same. When I passed in a variable to the function with a random each time it was called, then it was random each time. At least, that what I experienced in my program

In Gimp Scheme (Lisp derivative) I found that I needed to use the following:
(set! *seed* (car (gettimeofday)))
This is the Random Number Seed From Clock (seed is global)
You may also need:
(random-next)
This generates the next Random Number Using Seed
The non-truly random method is to set the seed:
(srand 12345)
; used in cases where the result is to be repeatable - useful in graphic design contexts.

Related

List the cartesian product of the list with itself [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
(defn slist-cartesian [lst]
(slist-iter
lst
(fn [x]
(slist-iter
lst
(fn [y]
(println x y))))))
So i have an entire code to explain but this part doesn't make sense to me, can someone please explain it to me ? I know list-iter is used when you'd like to see something done with each element of the list but i have trouble following the path here.
Let's assume that slist-iter does what you explained as list-iter behaviour, which is "'used' when you'd like to see something done with each element of the list"...
Now, I'm going to present you another way to do the cartesian product using Clojure core functions, so I can point you the key element that could be confusing you...
(defn slist-cartesian [lst]
(doseq [x lst
y lst]
(println x y)))
That is what doseq does. You can read it something like for each x in lst, and for each y in lst, print x and y.
Now, the key part here is that you are repeating lst both for x and y. That way we get the Cartesian product of lst with lst.
That is exactly what the code you show is doing. It is using lst as the list to be processed by both of the slist-iter calls.
Understand that it is needed to process the list each time from the beginning, to get what you are asking: The Cartesian product.
And now understand that you can do it both with the doseq expression and within the slist-iter functions.
Probably you need to understand why you can do it in the slist-iter form.
It is possible because fn creates a function and also that function is a Closure "which means that 'it' can access all the variables that were in scope when the function was created".
That means that that function slist-cartesian is creating with fn when calling the first slist-iter, has access to the parameter lst. Let's refer to that function as the anonymous one.
That anonymous function will be called again each time the first slist-iter begins to process a new element of lst, but lst is going to be the same slist-cartesian received and used when the later created the former.
I hope this answered your question.
If you still want to think and dig more in the subject, there is another way to think about this is by constructing the function one step at a time.
So in your own words ...
(defn slist-cartesian [lst]
(slist-iter
lst ;; The list with the elements
,,, ;; The thing to be done to the elements to the list
))
The thing to be done is a function that receive 1 parameter. That function will be called passing as an argument an element of the list, one element at a time for all the elements in the list.
If we make println the function, it will call it many times, one per element of the list, with such element as argument. Which means that it would print the whole list, one item at a time:
(defn slist-cartesian [lst]
(slist-iter
lst
println
))
(slist-cartesian '(1 2 3))
;; 1
;; 2
;; 3
What happens when you need to add more information to what is printed? You need a more complex function than simply println.
Let's create a function that will prefix a text to each item on the list and print them. Let's prefix the text "number: ". Because we have slist-iter we just only need to solve the problem of prefixing the text to a single number, with a function with only one parameter so it can be used by slist-iter and so solving the problem for all elements in the list. Let's make that solution a function:
(defn prefix-text-number-and-print [x]
(println "number: " x))
And now let's use it to build a function that prefix "number: " to all elements of a list and print them. Let's call that function prefix-text-number-to-each:
(defn prefix-text-number-to-each [lst]
(slist-iter
lst
prefix-text-number-and-print))
(prefix-text-number-to-each '(1 2 3))
;; number: 1
;; number: 2
;; number: 3
Cool. But what happen if we need to change the text of the prefix? That means that the function prefix-text-number-and-print needs to be generalized by adding a parameter for such prefix. But that will make that function useless for slist-iter. What then?
What we will do is to create the generalized function, and then somehow derive from it an specialized function we need on the precise moment.
(defn prefix-text-and-print [prefix, x] ;; Generalized function
(println prefix x))
So for the soon to be function prefix-text-to-each, we would do something like:
(defn prefix-text-to-each [prefix, x]
(slist-iter
lst
(somehow-derive-a-function prefix-text-and-print prefix))) ;; ATTENTION
There are many ways to create functions on the spot. You already used one tool for that in the code you show. You are using the function fn to build a function in place. Another way to do it is with the function partial. Let's explore the partial option first.
For that, I will do to prefix-text-and-print the opposite of what I did to prefix-text-number-and-print. I will specialize it. I will define prefix-text-number-and-print in terms of prefix-text-and-print. First by hand, and then by using partial:
;; By hand
(defn prefix-text-number-and-print [x]
(prefix-text-and-print "number: " x))
;; Using partial
(def prefix-text-number-and-print
(partial prefix-text-and-print "number: "))
Both definitions produce the same result: a function. Note the last one uses def instead of defn.
The definition using partial is simple a def. So it is simply defining prefix-text-number-and-print with whatever value is created by the call to partial.
partial creates a function. That new function will simply call the first parameter received by partial (in this case prefix-text-and-print) with the rest of the arguments partial received as arguments (in this case only "number: ") followed by the arguments the function itself receives.
Try it, it doesn't matter what version you used, the result will be the same:
(prefix-text-number-and-print 123)
;; number: 123
You could have done it in place of the call, with the same result
((partial prefix-text-and-print "number: ") 123)
;; number: 123
Now that you now how to use partial, let's use it to build a generalized function prefix-text-to-each
(defn prefix-text-to-each [prefix, lst]
(slist-iter
lst
(partial prefix-text-and-print prefix))) ;; ATTENTION
Let's try it:
(prefix-text-to-each "hola: " '(1 2 3)
;; hola: 1
;; hola: 2
;; hola: 3
Now we could think on making a function that combines not a text, but a list, with each element of another list. Again, we begin with combining the thing (a list) to a single element:
(def sufix-list-and-print [a-lst x] ;; Yeap, for practical reasons, let's suffix the thing (the list) instead of prefixing.
(slist-iter
a-lst
(partial prefix-text-and-print x ;; we are reusing this function, why not?
)))
(sufix-list-and-print '(1 2 3) 88)
;; 88 1
;; 88 2
;; 88 3
With that function, we can now create the function that combines 2 lists:
(def print-2-lsts-combined [a-lst b-lst]
(slist-iter
b-lst
(partial prefix-list-and-print a-lst)))
Let's try that:
(print-2-lsts-combined '(1 2 3) '(10 20 30))
;; 1 10
;; 1 20
;; 1 30
;; 2 10
;; 2 20
;; 2 30
;; 3 10
;; 3 20
;; 3 30
It happens that if the 2 lists are the same, you will have the Cartesian product. So you can define the Cartesian product in terms of this function:
(defn slist-cartesian [lst]
(print-2-lst-combined lst lst))
Or by itself in a similar way to the print-2-lst-combined function, which resembles the code you show originally:
(def slist-cartesian [lst]
(slist-iter
lst
(partial prefix-list-and-print lst) ;; ATENTION
))
Now, the original code uses fn instead of partial. fn and partial have the same job: to create a function.
Do you see it?
The problem in the list commented with ATTENTION was to give somehow the list lst to a function that receives only 1 parameter and you couldn't use that parameter for such purpose.
So the solution with partial was to derive such function.
The solution with fn was to express that function in place, and "say" the word lst when needed, because it could due to it being a Closure, as explained before. That is an anonymous function and I invite you to read more about it.

How to write functions of functions in Scheme

I am supposed to write a function called (nth-filtered f n), where f is a function of one variable and n is a natural number, which evaluates to the nth natural number such that f applied to that number is #t.
If we called
(nth-filtered even? 1) we would get 2
(nth-filtered prime? 10) we would get 29
How do I make it so that it works for any sequential function? What should I think about when approaching this type of problem?
A variable is a variable and + is also a variable. The main difference between a function and some other data type is that you can wrap a function name in parentheses with arguments and it will become a new value.
eg.
(define (double fun)
(lambda (value)
(fun (fun value))))
(define (add1 v)
(+ 1 v))
(define add2 (double add1))
(add2 1) ; ==> 3
Now the contract doesn't say so you deduct by looking that you do (fun ...) that fun needs to be a function. Imagine this:
(define test (double 5)) ; probably works OK
(test 1)
The last one fails since you get application: 5 is not a procedure or something similar. The error message is not standardized.
How to attack your task is by making a helper that has the same arguments as your function but in addition the current number that I guess starts at 1. As I demonstrated you use the function variable as a function and recurse by always increasing the number and reducing n when the f call was #t. The actual function will just use the helper by passing all the parameters in addition to your state variable.
Your problem requires a fold, which is the standard way to iterate other a list while keeping a record of things done so far.
Here a very rackety method using for/fold:
(define (nth-filtered predicate index)
(for/fold ([count 0]
[current #f] #:result current)
([n (in-naturals 1)]) ; we start at 1 but we could start at 0
#:break (= count index)
(values (if (predicate n) (add1 count) count)
n)))
for/fold takes a list of initial state. Here we define count as the number of times the given predicate returned #t and current as the currently tested value.
Then it takes a list of iterators, in this case we only iterate infinitely over (in-naturals).
To make it stop, we provide a #:break condition, which is "when the number of truthy predicates (count) is equal to the requested amount (index)".
for/fold requests that it's body finishes with a list of values for each "state" variable, in order to update them for the next iteration. Here we provide two values: one is the new count, the other is just the current n.
You can try it out, it works as you requested:
> (nth-filtered even? 1)
2
> (require math/number-theory)
> (nth-filtered prime? 10)
29
> (nth-filtered prime? 5)
11

Having trouble with a function in Scheme

so i am trying to understand this piece of code, and after staring at it for far too long i decided to ask here if anyone could help me understand how and why it works
(define knock-knock
(letrec ([dig (lambda (i)
(cons (* i (list-ref knock-knock (- i 1)))
(dig (+ i 1))))])
(cons 1 (dig 1))))
the function is then called by name with the value:
(list-ref knock-knock 5)
So my main problem is that i can not see where the letrec would end. the other thing is that i am not given a list, so what is the 4th element in the list that i am supposed to reference in line 3?
First, a note: this is not normal Scheme, as it requires lazy evaluation.
In lazy evaluation, values are only computed when they are needed. So, for defining knock-knock, we can just do
(cons 1 <thunk: (dig 1)>)
i.e., we generate a pair, but we don't need the second element, so we defer its evaluation until later.
When we actually want to evaluate the second element, we will already have knock-knock defined, so we can reference it.
The next element is computed by taking the previous (i-1-st) element, and multiplies it by i. So this will generate the series {n!}: 1,1,2,6,24,...
A straightforward translation of this code to the (normally lazy) Haskell language goes like this:
knock :: [Int]
knock = 1 : dig 1
where dig i = (i * knock !! (i-1)) : dig (i+1)

Random Walk in Clojure

I have written the following piece of code for a random walk, which draws random values from {-1,1}.
(defn notahappyfoo [n]
(reverse (butlast (butlast (reverse (interleave (take n (iterate rand (- 0 1)))(take n (iterate rand 1))))))))
However, the code fails to generate a satisfactory walk. The main problem stems from the function rand. It's lower bound is 0, which forced the awkward code I wrote. Namely, the function interleave ends up causing wild shifts in the walk as values are forced to swing from positive to negative. It will be hard to garner any sense of a continuous path with this code.
I believe there should be an elegant form in Clojure to construct this walk. But I am not able to piece the right functions together to generate such a walk. The goals of the function I am looking to construct consist of lower and upper bounds for the random number. In the code above I have forced the interval -1 to 1. It would be nice to generalize this to -a and a. Moreover, how do I form a collection of random reals (floating points) between -a and a that has some notion of continuity?
You need a random function that takes a range
(defn myrand [a b]
(+ a (rand (- b a))))
You can then create a sequence
(def s (repeatedly #(myrand -1 1)))
finally you can use reductions to get a sample walk
(take 10 s)
(reductions + (take 10 s))

Floating point formatted to base 16

I am writing a Lisp program to approximate pi using a Spigot algorithm, one that finds a single digit at a time without needing any digits previously calculated. This one:
Supposedly goes one hexadecimal digit at a time, however testing it out we have consecutive calls (iterating over i) yielding Lisp's well-known fractions:
2F/F
6A/333
33D/4CB3
13C/3B79
And so forth. This is achieved using the format function with the ~x parameter:
(format t "~x" [some number])
Alternatively,
(format t "~d" [some number])
Yields the base 10 decimals:
3.1333334
0.12942614
0.042220525
0.020755336
However I want decimals in hexadecimal, for example if one round yielded 0.5 then I want 0.8; if the base 10 is 0.75 then I want 0.C. That way I can calculate see each hexadecimal digit of pi separately, which was my original reason for choosing this Spigot algorithm. I could also use a fraction of the form (n / 16^k), because this could easily be converted into a hexadecimal decimal.
Is this possible?
~x and ~d are formatting routines for integers, not floating point numbers (emphasis added):
22.3.2.2 Tilde D: Decimal
An arg, which should be an integer, is printed in decimal radix. ~D
will never put a decimal point after the number. … If arg is not an
integer, it is printed in ~A format and decimal base.
22.3.2.5 Tilde X: Hexadecimal
This is just like ~D but prints in hexadecimal radix (radix 16)
instead of decimal.
(As an aside, I think there's actually some ambiguity about what base ~x should print its argument in if it's not an integer. It comes down to whether "just like ~D but prints in hexadecimal" overrides just the integer arguments, or the all arguments.)
But what are these format directives actually doing? They're binding the values of *print-base* and *print-radix* and the documentation on those says that they only affect the printing of rational numbers:
Variable *PRINT-BASE*, *PRINT-RADIX*
*print-base* and *print-radix* control the printing of rationals. The value of *print-base* is called the current output base.
The value of *print-base* is the radix in which the printer will print
rationals. For radices above 10, letters of the alphabet are used to
represent digits above 9.
If the value of *print-radix* is true, the printer will print a radix
specifier to indicate the radix in which it is printing a rational
number. The radix specifier is always printed using lowercase letters.
If *print-base* is 2, 8, or 16, then the radix specifier used is #b,
#o, or #x, respectively. For integers, base ten is indicated by a trailing decimal point instead of a leading radix specifier; for
ratios, #10r is used.
Now, there are some floating point directives for format, and they're listed in 22.3.3 FORMAT Floating-Point Printers. Unfortunately, none of those do anything with different bases or radices, so you won't be able to print hexadecimals with them.
It looks like you'll end up having to write your own output routine, or find one in a library. Of course, you should probably implement it as a function that can be used with ~slash, so that you can still write things like:
(format t "~/hexadecimal/" 1/16)
It's actually not too hard to do this, so here's one way (but I won't guarantee that there are no bugs in this). It wouldn't be too hard to extend this to work with a user-provided base, and to make it a bit more like the other floating point printers (e.g., to add a + for positive numbers if # is provided, and to add support for widths, etc.).
(in-package #:common-lisp-user)
(defun hexadecimal (stream number colonp atp &rest args)
(declare (ignore colonp atp args))
(when (< number 0)
(write-char #\- stream)
(setq number (- number)))
(multiple-value-bind (quotient remainder) (floor number 1.0)
(format stream "~x." quotient)
(do () ((zerop remainder))
(multiple-value-setq (quotient remainder)
(floor (* 16 remainder)))
(format stream "~x" quotient))))
With this, you get the expected results:
(LOOP :FOR NUM :FROM -1/2 :TO 1/2 :BY 1/256
:COLLECT (FORMAT NIL "~/hexadecimal/" NUM))
;=>
("-0.8" "-0.7F" "-0.7E" "-0.7D" "-0.7C" "-0.7B" "-0.7A" "-0.79" "-0.78"
"-0.77" "-0.76" "-0.75" "-0.74" "-0.73" "-0.72" "-0.71" "-0.7" "-0.6F"
...
"-0.1D" "-0.1C" "-0.1B" "-0.1A" "-0.19" "-0.18" "-0.17" "-0.16" "-0.15"
"-0.14" "-0.13" "-0.12" "-0.11" "-0.1" "-0.0F" "-0.0E" "-0.0D" "-0.0C"
"-0.0B" "-0.0A" "-0.09" "-0.08" "-0.07" "-0.06" "-0.05" "-0.04" "-0.03"
"-0.02" "-0.01" "0." "0.01" "0.02" "0.03" "0.04" "0.05" "0.06" "0.07"
"0.08" "0.09" "0.0A" "0.0B" "0.0C" "0.0D" "0.0E" "0.0F" "0.1" "0.11"
...
"0.6C" "0.6D" "0.6E" "0.6F" "0.7" "0.71" "0.72" "0.73" "0.74" "0.75"
"0.76" "0.77" "0.78" "0.79" "0.7A" "0.7B" "0.7C" "0.7D" "0.7E" "0.7F"
"0.8")
In fact, it's really not hard to make this a bit more generic. Since we can pass arguments to format directives, we can take the printing base as an argument, and we can bind *print-base* to it at the same time, so we can just write in the body of the function, and we can do our numeric work with *print-base*:
(in-package #:common-lisp-user)
(defun floating (stream number colonp atp
&optional (*print-base* 10) (num-digits 10)
&rest args)
(declare (ignore colonp args))
;; If the number is negative, print the #\- and invert the number.
;; Otherwise, the number is non-negative, and if an # was provided
;; we print a leading #\+.
(cond
((minusp number)
(write-char #\- stream)
(setq number (- number)))
(atp
(write-char #\+ stream)))
;; Print number, which is now guaranteed to be positive. Begin by
;; taking its integer part and printing it, followed by a point.
;; Then, pull individual places and write them. This continues,
;; updating quotient and remainder by multiplying the remainder by
;; the base and taking the floor again until either the remainder
;; becomes zero, or we've reached the maximum number of digits.
(multiple-value-bind (quotient remainder) (floor number 1.0)
(write quotient :stream stream)
(write-char #\. stream)
(do ((num-digits num-digits (1- num-digits)))
((or (zerop remainder) (zerop num-digits)))
(multiple-value-setq (quotient remainder)
(floor (* *print-base* remainder)))
(write quotient :stream stream))))
;; 1/2 base 10 is a repeating decimal in base 3.
CL-USER> (format t "~3/floating/" 1/2)
0.1111111111
;; so is -1/2, and asking for more numbers gives them to us
CL-USER> (format t "~3,15/floating/" -1/2)
-0.111111111111111
;; but 1/3 base 10 is non repeating in base 3
CL-USER> (format t "~3,15/floating/" 1/3)
0.1
;; it's non-repeating in base 6, as well
CL-USER> (format t "~6,15/floating/" 1/3)
0.2
;; base 16 still works
CL-USER> (format t "~16/floating/" 189/256)
0.BD
;; and the # will give us a leading +
CL-USER> (format t "~16#/floating/" 189/256)
+0.BD
I don't think it is possible with the built in features of format1 However I'm sure someone with some fancy math could implement a function to do this.
1. I tested with SBCL v1.1.14. I tried (format t "~x" (coerce 2/32 'float)) which was the same as (format t "~d" (coerce 2/32 'float))

Resources