- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试通过研究 Problem 18 来学习 Ocaml来自欧拉计划。我知道我想做什么,只是不知道该怎么做。
我有三个列表:
let list1 = [1;2;3;4;5];;
let list2 = [ 6;7;8;9];;
let line = [9999];;
let rec meld3 l1 l2 accum =
if List.length l2 = 1 then
List.append accum [ (hd l2 + max (hd l1) (hd (tl l1)))]
else
(
List.append accum [ (hd l2 + max (hd l1) (hd (tl l1)))];
meld3 (tl l1) (tl l2) accum ;
)
;;
let fu = meld3 list1 list2 line ;;
List.iter print_int fu;;
最佳答案
好的,让我们分解你的代码。这是你的原件。
let rec meld3 l1 l2 accum =
if List.length l2 = 1 then
List.append accum [ (hd l2 + max (hd l1) (hd (tl l1)))]
else
(
List.append accum [ (hd l2 + max (hd l1) (hd (tl l1)))];
meld3 (tl l1) (tl l2) accum ;
)
hd
和
tl
.这种转变不是微不足道的。简化列表操作以更容易识别代码问题非常重要。如果
l2
则更明显地表明此函数失败。是空的。
let rec meld3 l1 l2 accum = match l1, l2 with
| x1::x2::xs, [y] -> (* here the length of l2 is exactly 1 *)
List.append accum [ y + max x1 x2 ]
| x1::x2::xs, y::ys -> (* here the length of l2 is at least 1 *)
( List.append accum [ y + max x1 x2 ]
; meld3 (x2::xs) ys accum
)
printf
),然后丢弃 e1 的结果。我认为您想要的是让 e1 的结果成为
accum
的新值用于递归调用。因此,我们没有丢弃 e1,而是将其设为参数(
这是计算实际发生变化的关键步骤 ):
let rec meld3 l1 l2 accum = match l1, l2 with
| x1::x2::xs, [y] -> (* here the length of l2 is exactly 1 *)
List.append accum [ y + max x1 x2 ]
| x1::x2::xs, y::ys -> (* here the length of l2 is at least 1 *)
(
meld3 (x2::xs) ys (List.append accum [ y + max x1 x2 ])
)
l2
的基本情况来解决这个问题。是空的:
let rec meld3 l1 l2 accum = match l1, l2 with
| x1::x2::xs, [] -> (* here the length of l2 is 0 *)
accum
| x1::x2::xs, y::ys -> (* here the length of l2 is at least 1 *)
(
meld3 (x2::xs) ys (List.append accum [ y + max x1 x2 ])
)
let rec meld3 l1 l2 accum = match l1, l2 with
| _, [] -> accum
| x1::x2::xs, y::ys -> meld3 (x2::xs) ys (List.append accum [ y + max x1 x2 ])
append
使代码二次。这是一个累积参数的经典问题,并且有一个经典的解决方案:以相反的顺序累积答案列表:
let rec meld3 l1 l2 accum' = match l1, l2 with
| _, [] -> List.rev accum'
| x1::x2::xs, y::ys -> meld3 (x2::xs) ys (y + max x1 x2 :: accum')
accum
至
accum'
;对于以相反顺序排列的列表,素数是常规的。最后一个版本是我编译的唯一版本,我还没有测试任何代码。 (我确实在我的另一个答案中测试了代码)。
关于Ocaml noobie Q——如何使用累加参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/524616/
我对编程非常陌生(所以我提前道歉),并且我无法弄清楚如何创建一个 for 循环来执行以下操作: 我要求用户输入两个变量(我将它们称为 x 和 y),然后我计算 x/y = z。我想提出这个两个变量输入
我正在尝试对 vector 使用累加函数 vector A; double B = 0; A.reserve(100); for(itr = 0; itr < 210; itr++) { t
如果我想累积 std::vector 的绝对值,我可以使用 lambda 来计算绝对值并将其添加到 std::accumulate #include int main (){ std::ve
所以我需要使用 accumulate 对 vector 中的一些 double 值求和,其中我的 VECTOR 实际上是指向对象的指针。 现在,当我将 accumulate 与 int 一起用于 in
假设我有一个 (None, 2)-shape 张量 indices 和 (None,)-shape 张量 values。这些实际行号和值将在运行时确定。 我想设置一个 4x5 张量 t,索引的每个元素
我有一小部分固定节点: , , , .每个节点的值可以是 1 或 0。此外,每个节点的权重分别为:1、2、3、4。不使用节点属性。如何使用 XSLT 1.0 将每个节点的值乘以其权重相加?示例:
目前我在下面有一个数据集,如果 ColA 为 0,我尝试累加该值,而如果 ColA 再次为 1,则将值重置为 0(再次重新开始计数)。 ColA 1 0 1
我是一名优秀的程序员,十分优秀!