Using trace with functions not defined by me - common-lisp

I'm using sbcl 1.4.6 and I have this behaviour:
* (trace string<)
(STRING<)
* (string< "hola" "pato")
0: (STRING< "hola" "pato")
0: STRING< returned 0
0
* (defun test-without-cond (str)
(string< "hola" str))
TEST-WITHOUT-COND
* (test-without-cond "pato")
0
If the function is allready defined in common lisp, I cannot use trace when using inside a user defined function. BUt this is not a problem if I define the function
* (defun my-string< (str) (string< str "hello"))
MY-STRING<
* (trace my-string<)
(MY-STRING<)
* (defun test-2 (str) (my-string< str))
TEST-2
* (test-2 "gato")
0: (MY-STRING< "gato")
0: MY-STRING< returned 0
0
Why is this happening?

What can be traced depends on the implementation and various settings.
For SBCL read the manual: Open Coding and Inline Expansion
But SBCL now also has an interpreter and it looks like you can trace calls to CL functions from interpreted code:
* (setf *evaluator-mode* :interpret)
:INTERPRET
* (trace string<)
(STRING<)
* (defun test-without-cond (str)
(string< "hola" str))
TEST-WITHOUT-COND
* (test-without-cond "pato")
0: (STRING< "hola" "pato")
0: STRING< returned 0
0
*
Note that one might need to be careful with tracing core functions, since they can be called a lot...

Related

How does F# implement let rec?

I am wondering how F# implements let rec, and I couldn't find an answer. As a preface, I'll address how Scheme implements letrec:
In Scheme, let is just syntactics sugar for a definition of a lambda and applying it:
(let ((x 1)) (+ x 2))
is transformed to
((lambda (x) (+ x 2)) 1)
(in each case the expression is evaluated to 3).
letrec is also syntactic sugar, but #f is passed as initial argument to the lambda's parameters, and set! expressions are injected before the letrec body, like in this transformation:
(letrec ((x 1)) (+ x 2)) => ((lambda (x) (begin (set! x 1) (+ x 2))) #f).
Considering that F# doesn't have an equivalent operator to Scheme's set!, how does it implement let rec? Does it declare the function's parameters as mutable, and then mutate them in the function's body?
In F#, let rec allows a reference to the binding from within the function before it has been bound. let rec doesn't have an implementation per se, because it is merely a compiler hint.
In this contrived example,
let rec even =
function 0 -> true | 1 -> false | x -> odd (x - 1)
and odd =
function 0 -> false | 1 -> true | x -> even (x - 1)
the compiled IL very unglamorously translates to:
public static bool even(int _arg1)
{
switch (_arg1)
{
case 0:
return true;
case 1:
return false;
default:
return odd(_arg1 - 1);
}
}
public static bool odd(int _arg2)
{
switch (_arg2)
{
case 0:
return false;
case 1:
return true;
default:
return even(_arg2 - 1);
}
}
All function definitions are statically compiled to IL.
F# ultimately is a language which runs on the CLR.
There is no meta-programming.

how to find number of occurrences in ML string list?

I am new to ML, here is my attemp to writing a function that receives:
list of strings L
string str
int counter
the function should return the number of occurrences of str in L
Here is my code:
(*
* return number of occurences of str in L
* count should be initialized to zero.
*)
fun aux_num_of_occur(L: string list) (str:string) (count:int) =
if null L then 0
else if str = hd(L) then
aux_num_of_occur tl(L) str (count+1)
else
aux_num_of_occur tl(L) str count
Those are the errors i got:
Error: case object and rules don't agree [tycon mismatch]
rule domain: string list * string * int
object: ('Z list -> 'Z list) * 'Y * 'X
in expression:
(case (arg,arg,arg)
of (L : string list,str : string,count : int) =>
if null L
then 0
else if <exp> = <exp> then <exp> <exp> else <exp> <exp>)
uncaught exception Error
raised at: ../compiler/TopLevel/interact/evalloop.sml:66.19-66.27
../compiler/TopLevel/interact/evalloop.sml:44.55
../compiler/TopLevel/interact/evalloop.sml:296.17-296.20
My Questions:
What is wrong with the syntax?
it is not clear to me what the error message says: what is a
rule and an object in this case?
how can i return a int by recursively calling a function? is it by passing to it a counter as an argument?
This is a classical mistake: tl(L) and tl L are the same thing -- you don't need parentheses for function application in ML-like languages, you just juxtapose the function and the argument(s).
So aux_num_of_occur tl(L) ... is the same thing as aux_num_of_occur tl L ..., i.e. you are trying to apply aux_num_of_occur to the tl function, not to a list of strings. Now, the tl function has type 'a list -> 'a list and that is what you see in the error message (with 'a being 'Z there).
I ought to say that this style with those null, hd, and tl functions is not very idiomatic in SML -- you could use pattern-mathing instead. It is also more convenient to make aux_num_of_occur local to prevent namespace pollution, prevent incorrect usage (you control the initial value of count). Additionally, this gives you the advantage of not passing str all the time when recursing further.
fun num_of_occur ss str =
let
fun loop [] count = count
| loop (s::ss) count =
if s = str
then loop ss (count + 1)
else loop ss count
in
loop ss 0
end
Notice that num_of_occur has a more general type ''a list -> ''a -> int, where ''a means any type with equality comparison. The compiler will generate a warning
Warning: calling polyEqual
which you can either ignore or add some type annotations to num_of_occur. See here for more detail.

SML syntactical restrictions within recursive bindings?

There seems to be syntactical restrictions within SML's recursive bindings, which I'm unable to understand. What are these restrictions I'm not encountering in the second case (see source below) and I'm encountering when using a custom operator in the first case?
Below is the case with which I encountered the issue. It fails when I want to use a custom operator, as explained in comments. Of the major SML implementations I'm testing SML sources with, only Poly/ML accepts it as valid, and all of MLton, ML Kit and HaMLet rejects it.
Error messages are rather confusing to me. The clearest one to my eyes, is the one from HaMLet, which complains about “illegal expression within recursive value binding”.
(* A datatype to pass recursion as result and to arguments. *)
datatype 'a process = Chain of ('a -> 'a process)
(* A controlling iterator, where the item handler is
* of type `'a -> 'a process`, so that while handling an item,
* it's also able to return the next handler to be used, making
* the handler less passive. *)
val rec iter =
fn process: int -> int process =>
fn first: int =>
fn last: int =>
let
val rec step =
fn (i: int, Chain process) (* -> unit *) =>
if i < first then ()
else if i = last then (process i; ())
else if i > last then ()
else
let val Chain process = process i
in step (i + 1, Chain process)
end
in step (first, Chain process)
end
(* An attempt to set‑up a syntax to make use of the `Chain` constructor,
* a bit more convenient and readable. *)
val chain: unit * ('a -> 'a process) -> 'a process =
fn (a, b) => (a; Chain b)
infixr 0 THEN
val op THEN = chain
(* A test of this syntax:
* - OK with Poly/ML, which displays “0-2|4-6|8-10|12-14|16-18|20”.
* - fails with MLton, which complains about a syntax error on line #44.
* - fails with ML Kit, which complains about a syntax error on line #51.
* - fails with HaMLet, which complains about a syntax error on line #45.
* The clearest (while not helpful to me) message comes from HaMLet, which
* says “illegal expression within recursive value binding”. *)
val rec process: int -> int process =
(fn x => print (Int.toString x) THEN
(fn x => print "-" THEN
(fn x => print (Int.toString x) THEN
(fn x => print "|" THEN
process))))
val () = iter process 0 20
val () = print "\n"
(* Here is the same without the `THEN` operator. This one works with
* all of Poly/ML, MLton, ML Kit and HaMLet. *)
val rec process =
fn x =>
(print (Int.toString x);
Chain (fn x => (print "-";
Chain (fn x => (print (Int.toString x);
Chain (fn x => (print "|";
Chain process)))))))
val () = iter process 0 20
val () = print "\n"
(* SML implementations version notes:
* - MLton, is the last version, built just yesterday
* - Poly/ML is Poly/ML 5.5.2
* - ML Kit is MLKit 4.3.7
* - HaMLet is HaMLet 2.0.0 *)
Update
I could work around the issue, but still don't understand it. If I remove the outermost parentheses, then it validates:
val rec process: int -> int process =
fn x => print (Int.toString x) THEN
(fn x => print "-" THEN
(fn x => print (Int.toString x) THEN
(fn x => print "|" THEN
process)))
Instead of:
val rec process: int -> int process =
(fn x => print (Int.toString x) THEN
(fn x => print "-" THEN
(fn x => print (Int.toString x) THEN
(fn x => print "|" THEN
process))))
But why is this so? An SML syntax subtlety? What's its rational?
It's just an over-restrictive sentence in the language definition, which says:
For each value binding "pat = exp" within rec, exp must be of the form "fn match".
Strictly speaking, that doesn't allow any parentheses. In practice, that's rarely a problem, because you almost always use the fun declaration syntax anyway.

{ returning a string from a function } EVAL: variable has no value

I'm unable to print the return value of return-str.
; return-str.lisp
(defun ask-for-input(str)
(princ str)
(let ((cmd (read-line)))
cmd))
(defun return-str()
(let ((data-str (ask-for-input "enter a string")))
(data-str)))
(princ return-str)
Executing the code above with clisp, I got:
$ clisp return-str.lisp
*** - EVAL: variable RETURN-STR has no value
Please help me on how to properly return a string from return-str.
Thank you.
Your parentheses are incorrect in a couple of places.
(data-str) should be replaced with data-str because data-str is not a function.
(princ return-str) should be replaced with (princ (return-str)) because return-str is a function.

Recursion with closures in Groovy 2.1.9

I am unable to call recursive closures in Groovy 2.1.9
def facRec = {long n->
return n>1 ? n * facRec(n - 1) : 1
}
I'm getting a TypeMissmatch
When the closure is being defined, it has no idea of the variable facRec as it has not yet been defined...
You can do:
def facRec
facRec = {long n->
return n>1 ? n * facRec(n - 1) : 1
}
To get around this, or you can wrap the inner into another closure and call the owner of that inner closure (though I would tend to do the above as it is easier to read):
def facRec = {long n->
{ -> n > 1 ? n * owner.call( n - 1 ) : 1 }()
}
It should be noted that both of these will fail for big values of n as you will overflow the stack
You can use trampoline to get round this:
def facRec
facRec = { n, count = 1G ->
n > 1 ? facRec.trampoline( n - 1, count * n ) : count
}.trampoline()

Resources