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

Haskell实现类SQL解释器时Join操作报错求助

Haskell Parsec SQL解释器:Map.union实现全外连接出错求助

我是Haskell新手,最近在用Parsec库开发一个类SQL的解释器,数据存在Haskell的Map结构里。目前已经搞定了添加表和插入数据的功能,但在尝试用Map.union实现两张表的全外连接时踩了坑,程序直接报错了。

具体情况说明

我原本想通过先实现左连接、右连接,再用Map.union把结果合并来做全外连接,但运行时直接抛出了重复键的错误(错误信息和截图附后)。我怀疑是不是Map.union的特性和全外连接的需求不匹配?毕竟全外连接需要保留两张表的所有列,而Map.union遇到重复键会直接覆盖旧值?

相关内容

测试用命令(来自我的命令文本文件)

CREATE TABLE users (id INT, name TEXT);
INSERT INTO users VALUES (1, 'Alice');
INSERT INTO users VALUES (2, 'Bob');
CREATE TABLE orders (id INT, user_id INT, amount INT);
INSERT INTO orders VALUES (101, 1, 50);
INSERT INTO orders VALUES (102, 3, 30);
SELECT * FROM users FULL JOIN orders ON users.id = orders.user_id;

关键代码片段

-- 定义的表和数据库类型
data Value = IntVal Int | StringVal String deriving (Show, Eq)
type Table = Map String [Value]  -- 键是列名,值对应列的所有数据
type Database = Map String Table

-- 我尝试实现的全外连接函数
fullJoin :: Table -> Table -> String -> String -> Table
fullJoin table1 table2 onCol1 onCol2 = Map.union leftJoined rightJoined
  where
    leftJoined = leftJoinImpl table1 table2 onCol1 onCol2
    rightJoined = rightJoinImpl table1 table2 onCol1 onCol2

-- 左连接的实现(简化版)
leftJoinImpl :: Table -> Table -> String -> String -> Table
leftJoinImpl t1 t2 col1 col2 = 
  Map.union t1 (getMatchedColumns t2 matchedRows)
  where
    matchedRows = -- 根据关联键匹配行的逻辑,省略具体实现
    getMatchedColumns tbl rows = -- 提取匹配行的列数据,省略具体实现

错误信息(来自截图)

*** Exception: Map.union: duplicate key "id"

我想请教的问题

  • 是不是Map.union本身就不适合用来实现全外连接的合并步骤?如果是的话,那应该用什么方法来合并两张表的列,同时处理重复列名的问题?
  • 用Haskell的Map结构来存储表数据,实现全外连接的正确思路应该是什么样的?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:19:29