ML匿名函数交替和 [英] ML anonymous function alternating sum

查看:161
本文介绍了ML匿名函数交替和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我在ML中的家庭作业,我必须使用fold函数和一个匿名函数将整数列表变成交替和。如果列表为空,则结果为0.这是迄今为止我所拥有的。我认为我所拥有的是正确的,但是我最大的问题是我无法弄清楚如何编写我作为一个匿名函数。任何帮助将不胜感激。

 好玩foldl f y nil = y 
| foldl f y(x :: xr)=
foldl f(f(x,y))xr;

val sum = foldl(op - )〜6 [1,2,3,4,5,6];

val sum = foldl(op - )〜4 [1,2,3,4];

val sum = foldl(op - )〜2 [1,2];

这些只是我测试过的一些例子,看看我的工作方式,我认为所有三个正确。

解决方案

有两种情况:一种是列表长度是偶数,另一种是列表长度是奇数。如果我们有一个 [a,b,c,d,e] 的列表,则交替和为 a - b + c - d + e 。您可以将其重写为

e - (d - (c - (b - a)))

如果列表的长度是偶数,例如 [a,b,c,d] ,那么我们可以把它的交替和写为:

code> - (d - (c - (b - a)))为了解决这两种情况,我们可以让我们的fold的累加器是一个三元组,其中第一个条目是正确的值,如果列表是奇数的,第二个条目如果列表是偶数,则是正确的值,第三个值告诉我们我们看过的元素的数量,最后我们可以使用它来知道答案是第一个还是第二个条目。

b
$ b

因此,一个匿名函数如

  fn(x,y,n)=> (x  - #1 y,〜(x +#2 y),n + 1)

工作,我们可以用foldl和(0,0,0)的起始累加器来使用它,所以

  fun alternate_sum xs = 
let
(v1,v2,n)= foldl(fn(x,y,n)=>(x - #1 y,〜(x +#2 y),n + 1 ))(0,0,0)xs
in
if n mod 2 = 0 then v2 else v1
end


For my homework assignment in ML I have to use the fold function and an anonymous function to turn a list of integers into the alternating sum. If the list is empty, the result is 0. This is what I have so far. I think what I have is correct, but my biggest problem is I cannot figure out how to write what I have as an anonymous function. Any help would be greatly appreciated.

    fun foldl f y nil = y
    | foldl f y (x::xr) = 
    foldl f(f(x,y))xr;

    val sum = foldl (op -) ~6[1,2,3,4,5,6];

    val sum = foldl (op -) ~4[1,2,3,4];

    val sum = foldl (op -) ~2[1,2];

These are just some examples that I tested to see if what I had worked and I think all three are correct.

解决方案

There are two cases: one when the list length is even and one when the list length is odd. If we have a list [a,b,c,d,e] then the alternating sum is a - b + c - d + e. You can re-write this as

e - (d - (c - (b - a)))

If the list has an even length, for example [a,b,c,d] then we can write its alternating sum as

- (d - (c - (b - a))).

So to address these two cases, we can have our accumulator for fold be a 3-tuple, where the first entry is the correct value if the list is odd, the second entry is the correct value if the list is even, and the third value tells us the number of elements we've looked at, which we can use to know at the end if the answer is the first or second entry.

So an anonymous function like

fn (x,y,n) => (x - #1 y, ~(x + #2 y), n + 1)

will work, and we can use it with foldl with a starting accumulator of (0,0,0), so

fun alternating_sum xs =
  let
    (v1, v2, n) = foldl (fn (x,y,n) => (x - #1 y, ~(x + #2 y), n + 1)) (0,0,0) xs
  in
    if n mod 2 = 0 then v2 else v1
  end

这篇关于ML匿名函数交替和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆