Posts Tagged lisp

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).

, ,

6 Comments

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)))

, , ,

Leave a comment

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)

,

Leave a comment

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)
  "Jump to previously stored bookmark position"
  (interactive "nJump To: ")
  (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))
    (global-set-key (read-kbd-macro (concat "C-c "
                                            (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.

,

Leave a comment

Matrix manipulation in scheme

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

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)

,

Leave a comment

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: