Consider the following code
(use 'midje.sweet)
(defn x2 [x] (* x x))
(def fs {:x2 x2})
(fact
(x2 1) => "one"
((:x2 fs) 1) => "one"
(against-background
(#'tweetfetcher.core-test/x2 1) => "one"))
which outputs
FAIL at (core_test.clj:177)
Expected: "one"
Actual: 1
FAILURE: 1 check failed. (But 32 succeeded.)
The first check is stubbed while the second use x2 as provided by the hashmap fs.
Considering I rule out referencing, why is (:x2 fs) not stubbed ?
Thanks for insights.
I'm not surprised it works this way. In (x2 1), it is known compile-time that x2 is the function defined as (defn x2 [x] (* x x)).
In ((:x2 fs) 1), we know, compile-time, that fs is {:x2 x2}, but we don't yet know the result of (:x2 fs). By that I mean the expression (:x2 fs) is not evaluated during fact expansion. It probably sees that (:x2 fs) is not a var that resolves to a function and therefore does nothing to associate it with our stub (inside against-background).
Related
I want to define the Thue-Morse Sequence (or the fair-sharing sequence) in terms of an initial element, 0, and the rule defining the next section of the list in terms of the entire list up until this point. i.e.
fair 0 = [0]
--fair 1 = [0,1]
--fair 2 = [0,1,1,0]
--fair 3 = [0,1,1,0,1,0,0,1]
fair n = fair (n - 1) ++ map (1-) (fair (n - 1))
This works fine to generate the list up to any predefined length, but it seems ineffective to not just define the entire list at once, and use take if I need a predefined amount.
My first attempt at defining the entire list was fair = 0 : map (1-) fair but of course, this populates the list as it goes, so it doesn't ever (need to) reenter the list (and returns [0,1,0,1,0,1...]). What I want is some way to define the list so that when it reaches a not-yet-defined element in the list, it defines the next 'chunk' by reentering the list only until that point, (rather than the computation 'chasing' the new values as they're produced), so the steps in computing the list would be akin to this procedure:
begin with initial list, [0]
map (1-) over the existing list, producing [1]
append this to the existing list, producing [0,1]
map (1-) over the existing list, producing [1,0]
append this to the existing list, producing [0,1,1,0]
map (1-) over the existing list, producing [1,0,0,1]
append this to the existing list, producing [0,1,1,0,1,0,0,1]
The Wikipedia article I linked above has a helpful gif to illustrate this process.
As I presume you can see, this would continue indefinitely as new elements are needed. However, I can't for the life of me find a way to successfully encode this in a recursive function.
I have tried
reenter f xs = reenter f (xs ++ map f xs)
fair = reenter (1-) [0]
But while the logic seems correct, it hangs without producing anything, probably due to the immediate recursive call (though I thought haskell's lazy evaluation might take care of that, despite it being a rather complex case).
As you noted, you can't do the recursive call immediately - you first need to return the next result, and then recursively call, as in your last try:
Prelude> reenter prev_list = inverted_prev_list ++ reenter (prev_list ++ inverted_prev_list) where inverted_prev_list = map (1-) prev_list
Prelude> f = [0] ++ reenter [0]
Prelude> take 20 f
[0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1]
Following is code in Racket, another functional programming language, using the steps listed in the question.
(define (f n)
(define (invert s) ; sub-function to invert the numbers
(list->string
(for/list ((i (string->list s)))
(if (equal? i #\0) #\1 #\0))))
(let loop ((c 1)
(s "0")) ; starting string is "0"
(if (> c n)
s
(loop (add1 c)
(string-append s (invert s))))))
Testing:
(f 1)
(f 2)
(f 3)
(f 4)
(f 5)
Output:
"01"
"0110"
"01101001"
"0110100110010110"
"01101001100101101001011001101001"
For infinite series:
(define (f)
(define (invert s)
(list->string
(for/list ((i (string->list s)))
(if (equal? i #\0) #\1 #\0))))
(let loop ((s "0"))
(define ss (string-append s (invert s)))
(println ss)
(loop ss)))
To run:
(f)
This may give some ideas regarding a Haskell solution to this problem.
I want to create a function that could read my 2 input lists and combine what are inside the lists in to 1 lists, which allows me to use this 1 list for another function.
I have tried to use let function
(defun sumup(p1 p2)
(let ((sum (append(list p1 p2)) ))
(format t "the sum is ~a" sum)
(poly sum)
) )
and when i enter the input lists
(sumup+ '(5 (x 2)) '(3 (x 2)))
it gives results as
the sum is ((5 (x 2)) (3 (x 2)))
the poly term is (8 (x 2))
Here is the function poly, which will read the input list, and do the addition.
(defun poly (p1)
(let((x1(car(car(cdr(car p1))))) (x2(car(car(cdr(car(cdr p1))))))
(e1(car(cdr(car(cdr(car p1)))))) (e2(car(cdr(car(cdr(car(cdr p1)))))))
(c1(car(car p1))) (c2(car(car(cdr p1))))
(remainder(cdr(cdr p1)))
)
(if(and(null remainder)(null c2))
(format t "the poly term is (~a (~a ~a))" c1 x1 e1)
)
(if(and(equal x1 x2)(equal e1 e2))
(poly(append (list(list(+ c1 c2)(list x1 e1))) remainder)))
)
)
so with this function poly
(poly '((5(x 3))(3(x 3))(1(x 3))(4(x 3))))
you will get
the poly term is (13 (x 3))
so my chosen format to represent 5x^2 will be (5(x 2)) this is why i quote.
the sumup function is able to combine 2 terms now,but if
(sumup+ '(5 (x 2)) '((3 (x 2)) (2 (x 2))))
i will get
the sum is ((5 (x 2)) ((3 (x 2)) (2 (x 2))))
how can i change it to be ((5 (x 2)) (3 (x 2)) (2 (x 2)) which can be use for poly function?
The expression '(sum) denotes a list literal. It is a shorthand for the quote operator, and means exactly the same thing as (quote (sum)).
The quote operator suppresses evaluation of its argument as an expression and produces the argument literally; i.e. it means "don't try to call a function called sum; just give me the actual list (sum): a one element list containing the symbol sum".
So for instance (quote (+ 2 2)) or, using the usual shorthand, '(+ 2 2) returns (+ 2 2), literally. If we drop the quote, and evaluate (+ 2 2) then we get 4.
Now if we take '(sum) and simply drop the quote, it won't work, because now we're evaluating the form (sum) which expresses a call to a function whose name is sum, with no arguments. Of course, no such function exists, so the call is erroneous.
There is a special kind of "energized quote" in Lisp which resembles the regular quote. It is called backquote. To use the backquote, we replace the apostrophe ' shorthand with a backtick: `.
Like quote, backquote suppresses evaluation. However, inside a backquote, we can indicate elements which are exceptions to the "do not evaluate" rule, by preceding them with the comma, like this:
`(,sum)
If we have a variable called sum which holds a list (or any other object) and in that scope we evaluate the above backquote, that backquote will compute a list of one element which contains that object. Exactly as if we evaluated the expression (list sum).
More complicated quasiquote example:
(let ((a "hello")
(b 42))
`(1 2 3 ,a 4 ,b b ,(+ 2 2) (+ 2 2)))
-> (1 2 3 "hello" 4 42 b 4 (+ 2 2))
The objects inside the backquote not preceded by a comma are all taken literally: the b is not evaluated as a variable but stays b, the (+ 2 2) stays (+ 2 2) and isn't reduced to 4, unlike the ,(+ 2 2).
Incidentally, inside the poly function, you have this expression:
(append (list (list (+ c1 c2) (list x1 e1))) remainder)
This is a little hard to read. Even though no quoted material is being used, it is still an excellent target for the application of the backquote. With backquote, we can rewrite the expression like this:
`((,(+ c1 c2) (,x1 ,e1)) ,#remainder)
All the distracting clutter of the append and list calls goes away, and we just see the shape of the list being constructed.
Technical note: the backquote isn't a shorthand for any specific form syntax in Common Lisp. Whereas 'X means (quote X), as discussed, `X doesn't have such a correspondence; how it works is different in different implementations of Common Lisp. The comma also doesn't have a specific target syntax. In the Lisp dialect known as Scheme, `X corresponds to (quasiquote X) and ,Y corresponds to (unquote Y). This is defined by the Scheme language and so is that way in all implementations. Backquote is also known as "quasiquote", especially among Scheme programmers.
Assuming defun implies common lisp. Append is defined here.
((5 (x 2))) is a list containing the list (5 (x 2)).
I suspect you are looking for
(sumup (5 (x 2)) (3 (x 2)) )
On the other hand, poly is being called with a quoted list of a single argument, so it's possible you actually want:
(poly sum)
Overall, I think we need to see poly. I'm not clear why you're quoting everything.
The range could be defined by maxInclude, maxExclude,minInclude,minExclude
(defn check-range [value maxInclude maxExclude minInclude minExclude] ...)
And the following should hold true.
(check-range 100 100 nil nil 10) ;; should return true since 100<=100 and 100>10
(check-range 100 nil 200 nil 10) ;; should return true since 100<200 and 100>10
(check-range 100 100 nil 101 nil) ;; should return false since 100<=101 is not true
Is there any simple solution? I am using a long code which looks like imperative solution. I think in clojure there must be some nice solutions.
update: my code is as below, but not complete and need help to complete it
(defn check-range [value maxInclude maxExclude minInclude minExclude]
(
let [value1 (if (and maxInclude (< value maxInclude)) false true)
value2 (if (and maxExclude (<= value maxExclude)) false true)
value3 (if (and minInclude (> value minInclude)) false true)
value4 (if (and minExclude (>= value minExclude)) false true)
]
;;; then how to combine value1,2,3,4 into final result as false or true.
)
)
)
I'm not sure what it means for a range to have both an inclusive and exclusive maximum (or similarly, minimum). It seems like those options should be mutually exclusive, which suggests you shouldn't let clients opt into choosing both. Otherwise, how do you decide if it's more important for inclusion to win, or exclusion? The choice seems like it would have to be pretty arbitrary.
I suggest that it would be better to have a different way of constructing the range. This would have the additional benefit of avoiding all the nil hoops you're talking about jumping through and let users be explicit about the kind of range that they're making.
Perhaps something like:
(defn make-range-checker [bottom-check top-check]
(fn [n]
(and (bottom-check n)
(top-check n))))
So that for your initial 3 examples, you'd do something like these to create range-checking functions that you could apply to your input of 100:
(make-range-checker (partial < 10) (partial >= 100))
(make-range-checker (partial < 10) (partial > 200))
(make-range-checker (partial <= 100) (partial > 101))
(your third example is not correct, incidentally: "100<=101 is not true")
Someone wanting to create a range that extends to infinity in either direction could simply pass a predicate that always returns true.
(make-range-checker (partial < 10) (constantly true))
(make-range-checker (constantly true) (partial > 10))
I am just curious about these two functions in Lazy.
Lazy.from_fun
From the doc:
val from_fun : (unit -> 'a) -> 'a t
from_fun f is the same as lazy (f()) but slightly more efficient.
I then had a look at the source
let from_fun (f : unit -> 'arg) =
let x = Obj.new_block Obj.lazy_tag 1 in
Obj.set_field x 0 (Obj.repr f);
(Obj.obj x : 'arg t)
I guess Obj is used to directly allocate memories for from_fun. But why exactly does it boost the efficiency? or what is the difference between Lazy.from_fun and lazy (f())?
Lazy.from_val
val from_val : 'a -> 'a t
from_val v returns an already-forced suspension of v.
This is for special purposes only and should not be confused with lazy (v).
I really do not understand these. To me, Lazy.from_val 5 and lazy(5) both returns int lazy.t which has a concrete value of 5. Why is Lazy.from_val is for special purposes? and what kind of special purposes?
It's just my guess: let's compare the following:
let z1 = lazy (print_newline ())
let z2 = Lazy.from_fun print_newline
using ocamlc -dlambda:
(setglobal Lz!
(let
(z1/1008 =
(makemutable 246
(function param/1012 (apply (field 31 (global Pervasives!)) 0a)))
z2/1009 =
(apply (field 2 (global Lazy!)) (field 31 (global Pervasives!))))
(makeblock 0 z1/1008 z2/1009)))
z1 is a lazy value created from a function of the code function param/1012 -> Pervasives.print_newline (), while z2 is created directly from Pervasives.print_newline. z1 can be slightly inefficient because of the extra lambda abstraction.
Just as the documentation says, Lazy.from_val simply creates a lazy value from an already computed value without any suspension. You can check it by trying Lazy.from_val (print_string "hello") and lazy (print_string "hello"). The former immediately prints hello, but the latter does not.
I wanted to define a membership relation in Z3 with C++ APIs. I thought of doing it in the following way:
z3::context C;
z3::sort I = C.int_sort();
z3::sort B = C.bool_sort();
z3::func_decl InSet = C.function("f", I, B);
z3::expr e1 = InSet(C.int_val(2)) == C.bool_val(true);
z3::expr e2 = InSet(C.int_val(3)) == C.bool_val(true);
z3::expr ite = to_expr(C, Z3_mk_ite(C, e1, C.bool_val(true),
Z3_mk_ite(C,e2,C.bool_val(true),C.bool_val(false))));
errs() << Z3_ast_to_string(C,ite);
In this example the set is composed by the integer 2 and 3. I am sure there is a better way to define a relation, in particular a set membership relation, but I am really a Z3 rookie. Does anyone know the best one?
In Z3, sets are usually encoded using predicates (as you did) or arrays of Boolean. In the Z3 C API, there are several functions for creating set expressions: Z3_mk_set_sort, Z3_mk_empty_set, Z3_mk_set_union, ... Actually, these functions are creating array expressions. They represent a set of T as an array from T to Boolean. They use the encoding described in this article.
Remarks: in Z3, InSet(C.int_val(2)) == C.bool_val(true) is equivalent to InSet(C.int_val(2)). The InSet function is a predicate. We can write std::cout << ite instead of std::cout << Z3_ast_to_string(C, ite).
In the approach based on predicates, we usually need to use quantifiers.
In your example, you are saying that 2 and 3 are elements of the set, but to say that nothing else is an element, we need a quantifier. We also need quantifiers to state properties such as: set A is equal to the union of sets B and C.The approach based on quantifiers is more flexible, we can say for example that A is a set containing all elements between 1 and n.
The drawback is that it is really easy to create formulas that are not in decidable fragments that Z3 can handle. The Z3 tutorial describes some of these fragments. Here is an example from the tutorial.
;; A, B, C and D are sets of Int
(declare-fun A (Int) Bool)
(declare-fun B (Int) Bool)
(declare-fun C (Int) Bool)
(declare-fun D (Int) Bool)
;; A union B is a subset of C
(assert (forall ((x Int)) (=> (or (A x) (B x)) (C x))))
;; B minus A is not empty
;; That is, there exists an integer e that is B but not in A
(declare-const e Int)
(assert (and (B e) (not (A e))))
;; D is equal to C
(assert (forall ((x Int)) (iff (D x) (C x))))
;; 0, 1 and 2 are in B
(assert (B 0))
(assert (B 1))
(assert (B 2))
(check-sat)
(get-model)
(echo "Is e an element of D?")
(eval (D e))
(echo "Now proving that A is a strict subset of D")
;; This is true if the negation is unsatisfiable
(push)
(assert (not (and
;; A is a subset of D
(forall ((x Int)) (=> (A x) (D x)))
;; but, D has an element that is not in A.
(exists ((x Int)) (and (D x) (not (A x)))))))
(check-sat)
(pop)