## Using exceptions to simulate tail recursion in JavaScript

JavaScript is very powerful language but it don’t have tail call elimination. But it turn out that you can simulate it using exception system. Here is very simple recursive function that calculate factorial:

```function factorial(n) {
function recur(n, result) {
if (n == 0) {
throw result;
} else {
recur(n-1, result*n);
}
}
try {
recur(n, 1);
} catch(e) {
return e;
}
}
```

It turn out that in JavaScript (I read that in Douglas Crockford book JavaScript: The Good Parts) you can use any expression in throw and it will be send to variable in catch statement.

So what the above code does it simple exit from the recursive loop and pass result to catch statement. And this is exactly what tail recursion is, in language scheme this happen by default when inner function (you also need to create inner function in scheme) have recursive call as last expression. Here is scheme version of tail recursive factorial:

```(define (factorial n)
(let recur ((n n) (result 1))
(if (= n 0)
result
(recur (- n 1) (* result n)))))
```

the code use named let but it can be rewriten with inner function and invocation. (this kind of trick is needed in script-fuGimp extension based on scheme).

## ERC notifications on channels where there was activity after some inactivity

I need to monitor few IRC channels and I use Emacs so I write simple elisp function that I append to `erc-insert-pre-hook` and it notify me when there is some activity on those channels. I made this mainly because I what to know if someone visit `#openclipart` channel (because people where visiting ask question and leave after few minutes, there is no much activity on this channel)

``` (setq inactivity-buffer-alist '(("#openclipart" (inactivity . 900)) ("#hackerrank" (inactivity . 900)) ("#aiki" (inactivity . 900)))) (defun channel-activity (string &rest ignore) "notification when there is activity on a erc channel after inactivity" (let* ((buffer (buffer-name)) (buffer-alist-pair (assoc buffer inactivity-buffer-alist)) (buffer-alist (cdr buffer-alist-pair)) (current-time (current-time))) (if (not (null buffer-alist)) (let ((last-time-pair (assoc 'last-time buffer-alist)) (inactivity (cdr (assoc 'inactivity buffer-alist)))) (if (not (and (string-match "^\\*\\*\\*" string) (string-match "[freenode-info]" string))) (progn (if (or (null last-time-pair) (> (float-time (time-subtract current-time (cdr last-time-pair))) inactivity)) (async-exec-command "mpg123 -q /home/kuba/Pobrane/beep-6.mp3")) (if (null last-time-pair) (setf (cdr buffer-alist-pair) (append buffer-alist (list (cons 'last-time current-time)))) (setf (cdr last-time-pair) current-time)))))))) (add-hook 'erc-insert-pre-hook 'channel-activity) ```

You can add your channels to `inactivity-buffer-alist` along with time of inactivity (in miliseconds)

The function I use for notification is play sound using `(async-exec-command "mpg123 -q /home/kuba/Pobrane/beep-6.mp3")` – normal shell command was stoping execution of Emacs for few seconds

The code for this function is as follow

``` (defun async-exec-command (command &rest success) (interactive) (let* ((buffer-name (generate-new-buffer-name "**shell**")) (buffer (get-buffer-create buffer-name)) (process (apply #'start-process (append (list buffer-name buffer) (split-string command " "))))) (lexical-let ((buffer buffer) (success (car success)) (command command)) (set-process-sentinel process (if success (lambda (process str) (if (string= str "finished\n") (save-excursion (set-buffer buffer) (let ((content (buffer-string))) (kill-buffer buffer) (funcall success content))))) (lambda (proces str) (kill-buffer buffer))))) (concat "execute: " command))) ```

## Switching between buffers with the same major mode in Emacs

Below are functions that can be used to switch to next or previus buffer in the same major mode

```(defun buffer-same-mode (change-buffer-fun)
(let ((current-mode major-mode)
(next-mode nil))
(while (not (eq next-mode current-mode))
(funcall change-buffer-fun)
(setq next-mode major-mode))))

(defun previous-buffer-same-mode ()
(interactive)
(buffer-same-mode #'previous-buffer))

(defun next-buffer-same-mode ()
(interactive)
(buffer-same-mode #'next-buffer))
```

In my init file I have bind those functions to CTRL+TAB and CTRL+ALT+TAB which was not set by default.

```(global-set-key [C-M-tab] 'previous-buffer-same-mode)
(global-set-key [C-tab] 'next-buffer-same-mode)
```

## Faster buffer bookmarking in Emacs

I wanted to speed up jumping in the same buffer so I have written this bookmarking utility (Similar to built-in registers) and put it in my .emacs file.

```(defvar bookmark-markers '())

(defun bookmark (bookmark)
"Store current position for this buffer in
bookmar-markers a-list"
(interactive "nBookmark: ")
(let* ((buffer (current-buffer))
(bookmarks
(let ((pair (assoc buffer bookmark-markers)))
(if (eq pair nil)
(let ((new-pair (cons buffer '())))
(progn
(setq bookmark-markers
(append bookmark-markers
(list new-pair)))
new-pair))
pair))))
(let ((pair (assoc bookmark bookmarks)))
(if (eq pair nil)
(setf (cdr bookmarks)
(append (cdr bookmarks)
(list (cons bookmark (point)))))
(setf (cdr pair) (point))))))

(defun jump-to-bookmark (bookmark)
(let ((pair-bookmars (assoc (current-buffer) bookmark-markers)))
(if (not (eq pair-bookmars nil))
(let ((pair-point (assoc bookmark (cdr pair-bookmars))))
(if (not (eq pair-point nil))
(goto-char (cdr pair-point)))))))

(defun range (n &optional list)
"function return list of numbers from 1 to n"
(if (eq n 0)
list
(let ((n (- n 1)))
(range n (cons n list)))))

(dolist (i (range 9))
(number-to-string i)))
;; emacs lisp have no closures
(lexical-let ((i i))
(lambda ()
(interactive)
(jump-to-bookmark i)))))

(global-set-key (kbd "C-c 0") 'bookmark)
```

Above code define 2 functions `bookmark` bind to `C-c 0` and function `jump-to-bookmark` this function create a bookmark, for currect position in a buffer, and assing it to the number (passed as argument or from minubuffer, if run interactively). You have 9 keyboard binding for keys from `C-c 1` to `C-c 9`.

You can use it go to specific location and type `C-c 0 1 RET` go to another location and type `C-c 0 2 RET` and now you can jump to locations with `C-c 1` or `C-c 2`.

Every buffer will have they own bookmarks.

## Matrix manipulation in scheme

Here’s the code I wrote for matrix manipulation in scheme. It use lists.

If you want to play with the code online you can use LIPS: Scheme based lisp interpreter in JavaScript. On the website you can find bookmark, that create Scheme REPL on any website, including this one.

### Procedure that creates new square identity matrix:

``````(define (make-matrix n)
(let outter ((i n) (result '()))
(if (= i 0)
result
(outter (- i 1)
(cons
(let inner ((j n) (row '()))
(if (= j 0)
row
(inner (- j 1) (cons (if (= i j) 1 0) row))))
result)))))
``````

### Procedure that return nth element of the list, which is the same as nth row of the matrix:

``````(define (nth list n)
(let iter ((n n) (result list))
(if (= n 0)
(car result)
(iter (- n 1)
(cdr result)))))

(define matrix-row nth)
``````

### Procedure that return nth column of the matrix:

``````(define (matrix-col M n)
(let iter ((i (length M)) (result '()))
(if (= i 0)
result
(iter (- i 1)
(cons (nth (nth M (- i 1)) n) result)))))
``````

### Procedure for multiplication of two matrices:

``````(define (matrix-mul N M)
(let rows ((i (length N)) (result '()))
(if (= i 0)
result
(rows (- i 1)
(cons
(let cols ((j (length (car M))) (row '()))
(if (= j 0)
row
(cols
(- j 1)
(cons (reduce + (map *
(matrix-row N (- i 1))
(matrix-col M (- j 1))))
row))))
result)))))
``````

### For above procedure you will need reduce procedure:

``````(define (reduce fun lst)
(let iter ((result (car lst)) (lst (cdr lst)))
(if (null? lst)
result
(iter (fun result (car lst)) (cdr lst)))))``````

### Procedure for multiplication of vector and matrix:

``````(define (matrix-vector-mul v M)
(car (matrix-mul (list v) M)))
``````

### Procedure for transpose the matrix:

``````(define (matrix-transpose M)
(if (null? (car M))
'()
(cons (map car M)
(matrix-transpose (map cdr M)))))
``````

### Tail recursive procedure for transpose the matrix:

``````(define (matrix-transpose M)
(let iter ((M M) (result '()))
(if (null? (car M))
result
(iter (map cdr M) (append result (list (map car M)))))))
``````

### Procedure that calculate the sum of two matrices:

``````(define (matrix-sum N M)
(let iter ((N N) (M M) (result '()))
(if (or (null? N) (null? M))
(reverse result)
(iter (cdr N)
(cdr M)
(cons (map + (car N) (car M)) result)))))
``````

### Shorter version of the above:

``````(define (matrix-sum N M)
(map (lambda (nrow mrow) (map + nrow mrow)) N M))
``````

### Usage:

You can use those procedures like this:

``````(define M1 '((1 2 3) (2 3 4) (3 2 1)))
(define M2 (make-matrix 3))

(write (matrix-mul M1 M2))
(newline)
(write (matrix-mul M1 '((2 3 1) (1 2 1) (1 3 1))))
(newline)
(write (matrix-sum M1 M2))
(newline)
(write (matrix-vector-mul '(2 3 1) M1))
``````

## How to use and extend BiwaScheme

BiwaScheme is scheme implementation in Javascript.

Here you can find scheme interpeter using BiwaScheme (using JQuery Terminal Emulator inside JQuery UI Dialog). If you want to download BiwaScheme package click here.

BiwaScheme use prototype jQuery javascript library.

If you want to use interpreter in your own code you must:

`http://src/development_loader.js`

or if you want to make distribution you must have make and YUI Compressor which require java
Uncomress package and type make in biwascheme directory it will create lib/biwascheme.js file which is compressed library. You must put it in head of your html file:

`lib/biwascheme.js`
• Create instance of Interpreter class
`var intepreter = new BiwaScheme.Interpreter();`
• You can also put function for error handling to the constructor
```var biwascheme = new BiwaScheme.Interpreter(function(e, state) {
\$('output').innerHTML += e.message;
});
```
• If you want to result be proper displayed you must overwrite puts function
```var output = \$('ouptut');
function puts(str, no_newline) {
if (no_newline) {
output.innerHTML += str;
} else {
output.innerHTML += str + "<br />";
}
}
```
• Evaluating funtion should look like this:
```var input = \$('input');
var output = \$('output');
function scheme_eval(e) {
try {
var code = input.html();
// show trace messages
if (trace) {
var opc = interpreter.compile(code);
var dump_opc = (new BiwaScheme.Dumper()).dump_opc(opc);
output.innerHTML += dump_opc;
}
interpreter.evaluate(code, function(result) {
if (result != undefined) {
result = BiwaScheme.to_write(result);
output.innerHTML += '> ' + result + "\n";
}
});
} catch(e) {
//this will never be evaluated because all errors are
//pased to function pased to Interpreter constructor
output.innerHTML += e.message;
throw(e);
}
}
```
• You could bind this function with onclick event
`\$('eval_btn').click(scheme_eval);`
• If you want to define new function which will be accessable in your scheme interpreter you should use define_libfunc function from global object BiwaScheme. First parametr is scheme name of the function, second and third are minimum and maximum of parameters and fourth is the anonimus function with one argument which is array of parameters pased to scheme procedure.
```BiwaScheme.define_libfunc('env', 0, 0, function(args) {
var result = new Array();
for(fun in window.BiwaScheme.CoreEnv) {
result[result.length] = fun;
}
// result should be converted from array to scheme list
return result.to_list();
});
```

This function will return list of all function and variables in scheme global Environment.
The following scheme function will display that list:

```(define (show-env)
(let iter ((list (env)))
(if (not  (null? list))
(begin
(display (car list))
(newline)
(iter (cdr list))))))```

or simplier.

```(define (show-env)
(display (string-join (env) "\n"))
(newline))
```

• If you want to define some variable you must put it in BiwaScheme.CoreEnv array.

If you want to define (in javascript) function with scheme code use BiwaScheme.define_scmfunc. First parameter is scheme name, second and third are minimum and maximum of parameters (BiwaScheme check this before function are evaluated) and the fourth one is string containing your scheme code (should be lambda expresion).

```BiwaScheme.define_scmfunc('**', 1, 1,
"(lambda (x y) \
(cond \
((= y 0) 1) \
((< y 0) (** (/ 1. x) (- y))) \
(else \
(let iter ((i 1) (result x)) \
(if (= i y) \
result \
(iter (+ i 1) (* result x)))))))");```

Former function define power with tail recursion.

You could also create scheme macro in javascript with BiwaScheme.define_syntax function. This function must return BiwaScheme.Pair object which will be evaluated. It accept single parameter which is scheme expression (tree build from `BiwaScheme.Pair` objects). This is example of using macros from javascript:

```//this is helper Array method which traverse a tree build with arrays
//and create tree of Symbols
// it use to_list function wich is defined by BiwaScheme
Array.prototype.to_tree = function() {
for(var i in this) {
if (this[i] instanceof Array) {
return this[i].to_tree();
}
}
return this.to_list();
};

BiwaScheme.define_syntax('foo', function(expr) {
return [BiwaScheme.Sym("display"),
[BiwaScheme.Sym("quote"), expr.cdr.to_array().to_tree()]
].to_tree();
});
```

This code create new macro foo which simply display expression passed as parameters. Note that the whole expression is in expr.cdr filed.

• In interpeter you could also define macros (like common lisp macros) with define-macro expresion.
```(define-macro (for params . body)
`(let iter ((,(car params) ,(cadr params)))
(if (< ,(car params) ,(caddr params))
(begin
,@body
(iter (+ ,(car params) ,(if (= (length params) 4)
1)))))))
```

The former code define for loop (which use tail recursion), you could use it with `(for (variable init end step) code)`:

```(for (i 1 10)
(display i)
(newline))```

or

`(for (i 10 100 10) (display i) (newline))`

Which display numers: 10 20 30 40 50 60 70 80 90 100.

Update: Check also Extending Scheme interpreter in BiwaScheme wiki on GitHub.