Home > Software engineering >  Emacs: how to evaluate Haskell expressions in the comment section within the source file
Emacs: how to evaluate Haskell expressions in the comment section within the source file

Time:11-09

In the Haskell source code file:

-- >>> sin 5

Typing a shortcut key, you get the results below:

-- λ> sin 5
-- -0.9589242746631385
-- it :: Floating a => a
-- (0.03 secs, 133,480 bytes)

This feature is quite handy. Does anyone know how to do it with Emacs?

CodePudding user response:

I managed to modify the haskell-mode code:

(require 'subr-x)

(defun my-run-haskell-expr ()
  "Get haskell expression"
  (interactive)
  (search-backward "-- >>>")
  (setq my-expr
        (string-remove-prefix "-- >>>" (buffer-substring-no-properties (line-beginning-position) (line-end-position))))
  (my-haskell-interactive-mode-run-expr my-expr)
  )

(defun my-haskell-interactive-mode-run-expr (expr)
  "Run the given expression."
  (let ((session (haskell-interactive-session))
        (process (haskell-interactive-process)))
    (haskell-process-queue-command
     process
     (make-haskell-command
      :state (list session process expr 0)
      :go (lambda (state)
            ;; (goto-char (point-max))
            ;; (insert "\n")
            (end-of-line)
            (insert "\n")
            (beginning-of-line)
            (setq haskell-interactive-mode-result-end
                  (point-max))
            (haskell-process-send-string (cadr state)
                                         (haskell-interactive-mode-multi-line (cl-caddr state)))
            (haskell-process-set-evaluating (cadr state) t))
      :complete
      (lambda (state response)
        (haskell-process-set-evaluating (cadr state) nil)
        (unless (haskell-interactive-mode-trigger-compile-error state response)
          (my-haskell-interactive-mode-expr-result state response)))))))

(defun my-haskell-interactive-mode-expr-result (state response)
  "Print the result of evaluating the expression."
  ;; (mapc 'insert (split-string-and-unquote response))
  (mapc (lambda (str) (progn
                        (insert "-- ")
                        (insert str)
                        (insert "\n")))
        (split-string-and-unquote response "\n")))

(global-set-key (kbd "C-c C-e") 'my-run-haskell-expr)

;; end of haskell inline evaluation

Just bind the function my-get-haskell-expr to a shortcut and it will work.

  • Related