向列表添加 2 个元素的无点函数 / (:) 列表数据构造函数和 (.) 的双重应用

问题描述 投票:0回答:1

我正在努力正确定义该函数的无点版本,它将向列表中添加 2 个元素。

很容易想出一些简单的简单实现:

addTwoElems :: a -> a -> [a] -> [a]

addTwoElems x y xs = x : y : xs
addTwoElems x y    = (++) [x, y]
addTwoElems        = (.) `on` (:)  “ point free but with additional function

但是两个列表数据构造函数 (:)

无点组合 
(.) 会是什么样子?

请不仅展示正确的功能实现,还请解释如何获得正确版本背后的步骤和逻辑。

haskell syntax functional-programming pointfree type-constructor
1个回答
0
投票

根据评论,仅使用

.
:
的逐步推导:

addTwoElems x y xs = x : y : xs
-- rewrite the first : as a prefix function
addTwoElems x y xs = (:) x (y : xs)
-- rewrite the second : as a prefix function
addTwoElems x y xs = (:) x ((:) y xs)
-- use function composition to get xs out of the parentheses
addTwoElems x y xs = ((:) x . (:) y) xs
-- eta-reduce to get rid of xs
addTwoElems x y = (:) x . (:) y
-- rewrite the . as a prefix function
addTwoElems x y = (.) ((:) x) ((:) y)
-- use function composition to get y out of the parentheses
addTwoElems x y = ((.) ((:) x) . (:)) y
-- eta-reduce to get rid of y
addTwoElems x = (.) ((:) x) . (:)
-- rewrite the second . as an operator section, so that the part of the expression with x is last
addTwoElems x = (. (:)) ((.) ((:) x))
-- use function composition to get x out of the inner parentheses
addTwoElems x = (. (:)) (((.) . (:)) x)
-- use function composition to get x out of the outer parentheses
addTwoElems x = ((. (:)) . (.) . (:)) x
-- eta-reduce to get rid of x
addTwoElems = (. (:)) . (.) . (:)
© www.soinside.com 2019 - 2024. All rights reserved.