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

Haskell中如何实现多行字符串拼接?(GHC环境)

Haskell长字符串多行拼接的解决方法

Haskell是缩进敏感的语言,多行拼接报错通常是缩进不符合语法规则,以下几种方法可以解决:

方法1:调整缩进或把运算符放在行尾

如果坚持用++拼接,要么让后续行的代码和=右侧的第一个字符对齐,要么把++放在行尾,让GHC识别表达式未结束:

对齐式缩进

let str = "(\"" 
         ++ int_list_to_string (printed ctx) ""
         ++ "\",\"" 
         ++ int_list_to_string (stack ctx) ""
         ++ "\")"

运算符行尾式

这种方式更灵活,后续行只要缩进深度大于let的缩进即可:

let str = "(\"" ++
          int_list_to_string (printed ctx) "" ++
          "\",\"" ++
          int_list_to_string (stack ctx) "" ++
          "\")"

方法2:使用格式化函数简化拼接

用Text.Printf模块的格式化功能,代码可读性更强,多行拆分也更自然:

import Text.Printf

let str = printf "(\"%s\",\"%s\")" 
                (int_list_to_string (printed ctx) "")
                (int_list_to_string (stack ctx) "")

方法3:利用GHC扩展减少转义

开启GHC的准引号扩展,避免手动转义双引号,同时支持更清晰的多行拆分:

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
import Text.RawString.QQ

let printedStr = int_list_to_string (printed ctx) ""
    stackStr = int_list_to_string (stack ctx) ""
    str = [r|("|] ++ printedStr ++ [r|","|] ++ stackStr ++ [r|")|]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 14:12:11