haskell 无指针函数,用于向(:)列表数据构造函数和(.)的list / double应用程序添加2个元素

wi3ka0sx  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(131)

我正在努力正确定义函数的无点版本,它向列表中添加了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

但是两个列表数据构造函数(:)的 *point-free复合 *(.)看起来会是什么样子呢?
请不要只展示正确的函数实现,而是请解释如何获得正确版本的步骤和逻辑。

tpgth1q7

tpgth1q71#

根据评论,一步一步的推导,只使用.:

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 = (. (:)) . (.) . (:)

相关问题