You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Emacs如何实现Haskell源文件注释内的表达式求值功能

Emacs 实现Haskell注释行执行并插入结果的配置方法

前置准备

  • 先安装Haskell基础工具链:通过GHCup安装GHC、GHCi、cabal/stack,确保ghci命令可以在终端正常调用
  • Emacs安装haskell-mode包,可直接从MELPA源搜索安装

配置代码

将以下代码添加到你的Emacs配置文件(通常为~/.emacs或~/.config/emacs/init.el)中:

;; 可选:根据你的包管理工具设置ghci类型,二选一即可
;; (setq haskell-process-type 'stack-ghci)
;; (setq haskell-process-type 'cabal-repl)

(defun haskell-eval-and-insert-commented ()
  "识别当前行-- >>> 开头的注释,执行表达式并插入格式化的结果"
  (interactive)
  (save-excursion
    (beginning-of-line)
    (if (looking-at "^-- >>> \\(.*\\)$")
        (let* ((expr (match-string 1))
               (proc (haskell-process-get-or-create)))
          ;; 将>>>替换为λ>
          (replace-match "-- λ> \\1")
          ;; 向ghci发送命令,开启类型、耗时显示后执行表达式
          (haskell-process-queue-command
           proc
           (make-haskell-command
            :state (list (current-buffer) (point-at-eol))
            :command (concat ":set +s +t\n" expr "\n")
            :handler
            (lambda (state response)
              (destructuring-bind (buf insert-pos) state
                (with-current-buffer buf
                  (goto-char insert-pos)
                  ;; 逐行处理返回结果,添加注释前缀
                  (dolist (line (split-string (string-trim response) "\n"))
                    (unless (string-empty-p line)
                      (insert "\n-- " (string-trim line))))))))))
      (message "当前行不是-- >>> 开头的注释行"))))

;; 为haskell-mode绑定快捷键,这里用C-c C-e,可自行修改
(add-hook 'haskell-mode-hook
          (lambda ()
            (define-key haskell-mode-map (kbd "C-c C-e") #'haskell-eval-and-insert-commented)))

使用方法

  1. 打开Haskell源代码文件,先按C-c C-l加载当前文件到GHCi中,完成交互进程初始化
  2. 在需要执行测试的位置写注释行,格式为-- >>> 要执行的Haskell表达式,比如-- >>> sin 5
  3. 光标停留在该行,按下快捷键C-c C-e,即可自动生成要求的格式的执行结果

内容的提问来源于stack exchange,提问作者McBear Holden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 01:54:04