【发布时间】:2021-07-06 11:28:27
【问题描述】:
我正在尝试使用保护递归,但我在使用 Haskell 语法时遇到了困难。
我正在尝试在 Haskell 中使用递归来减少整数“n”次,直到达到我想要的基本情况,同时跟踪“n”,然后返回减少的整数和“n”作为我的一条信息的元组。
我的基本情况是整数在 1 到 13 之间。
例如,
Prelude> reduce 42
(3, 2)
Prelude> reduce 3
(3, 0)
为了解释逻辑,
Prelude> reduce 42
( (((42 - 13) - 13) - 13), 1+1+1+1 ) --> assume the accumulator = 0, hence 0,1,2.
(3, 3)
Prelude> reduce 3
(3, 0) --> already in base case!
目前,我有
reduce (x, 0)
| x `elem` [1 .. 13] = (x, acc)
| otherwise = reduce (x -13, acc + 1)
where
acc = 0
当然,我的 IDE 大喊我错了。我不知道如何在这个递归中实现初始化元组,这样它就像reduce :: a -> (a, b)
编辑:我想我越来越近了......但当然,我正在尝试将其实现为 a -> (a,b)。
【问题讨论】:
标签: haskell recursion accumulator