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

Haskell中如何组合swap和pair函数实现swapPair功能

Haskell swapPair 实现方案

完全可以用你提到的两个函数组合实现,只需要用到Haskell的函数组合运算符.即可,实现代码如下:

swapPair = swap . pair

实现原理

  • pair x y的作用是接收两个参数,返回由这两个参数组成的二元组(x, y)
  • swap的作用是接收一个二元组,返回元素交换位置后的新二元组
  • 函数组合运算符.的逻辑是:(f . g) x = f (g x),放在这个场景下,swap . pair会先调用pair拿到二元组,再把这个二元组输入给swap做交换,最终得到的效果和你定义的swapPair x y = (y, x)完全一致。

你可以直接在GHCi中测试验证效果:

swapPair 3 5 -- 运行结果为 (5,3)
swapPair "hello" "world" -- 运行结果为 ("world","hello")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:24:03