用SML编写多个功能-顺序组合 [英] Writing multiple functions in SML - Sequential Composition

查看:123
本文介绍了用SML编写多个功能-顺序组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解顺序合成比现在在SML中如何更好地工作。我必须编写一个程序,该程序需要一个整数列表,并将索引为零的整数移动到列表中的最后一个索引。即。 [4,5,6]-> [5,6,4]。

I would like to understand how sequential composition works much better than I do now in SML. I have to write a program that takes a list of integers and moves the integer at index zero to the last index in the list. ie. [4, 5, 6] -> [5, 6, 4].

我现在拥有的代码是:

- fun cycle3 x =
= if length(x) = 1 then x
= else (List.drop(x, 1);
= x @ [hd(x)]);
val cycle3 = fn : 'a list -> 'a list

问题出在我的else语句中,我想发生的事情是先连接第一个学期结束,然后第二个放下第一个学期。看起来很简单,我只是不了解如何使用SML按特定顺序执行多项功能。我的理解是,调用的第一个函数具有第二个函数的范围,第二个函数具有第三个函数的范围..等等等等。

The question lies in my else statement, what I want to happen is first concatenate the first term to the end, and then second drop the first term. It seems simple enough, I just don't understand how to perform multiple functions in a particular order using SML. My understanding was that the first function called has the scope of the second function that would have the scope of the third function.. etc etc.. What am I doing wrong here?

推荐答案

SML中的大多数内容都是不可变的-您的函数(而不是修改列表)正在构建新列表。 List.drop(x,1)计算出一个新列表,该列表包括除 x 的第一个元素以外的所有元素,但是不会修改 x

Most things in SML are immutable -- your function, rather than modifying the list, is building a new list. List.drop(x,1) evaluates to a new list consisting of all but the first element of x, but does not modify x.

要使用您的方法,您可以绑定的结果List.drop(x,1)转换为变量,如下所示:

To use your method, you would bind the result of List.drop(x,1) to a variable, as in the following:

fun cycle3 x = if length x = 1
               then x
               else let
                      val y = List.drop(x,1)
                    in
                      y @ [hd(x)]
                    end

或者,更干净的方法来做同样的事情,也可以解决空列表中的内容:

Alternately, a cleaner way of doing this same thing, that also handles the possibility of an empty list:

fun cycle3 [] = []
  | cycle3 (x::xs) = xs @ [x]

这篇关于用SML编写多个功能-顺序组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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