SML:为什么函数总是采用一个参数使语言变得灵活 [英] SML : why functions always take one-argument make language flexible

查看:254
本文介绍了SML:为什么函数总是采用一个参数使语言变得灵活的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从SML书中了解到,SML中的函数总是只有一个参数:一个元组。一个接受多个参数的函数只是一个函数,它将一个元组作为参数,用函数绑定中的元组绑定实现。我理解了这一点。



但是在此之后,这本书说了一些我不明白的东西:

这一点使得SML语言变得灵活而优雅的设计,并且您可以做一些您在Java中无法做到的有用功能。



为什么这个设计使语言变得灵活?什么是文本引用,SML可以但java不能?

解决方案

使用元组而不是多个参数增加了灵活性高阶函数可以与任何阵列的函数一起工作。例如,要创建列表 [fx,fy,fz] ,可以使用高阶函数 map 这:

  map f [x,y,z] 

这很简单 - 你可以用任何语言来做到这一点。但现在让我们考虑一下 f 实际需要两个参数的情况。如果 f 是一个真正的二元函数(假设SML有这样的函数),我们需要一个不同版本的 map 可以使用二元函数而不是一元函数(如果我们想使用3元函数,我们也需要一个版本)。然而,使用元组,我们可以像这样写:

  map f [(x,a),(y,b), (z,c)] 

这将创建列表 [f(x ,a),f(y,b),f(z,c)]

PS:需要多个参数在SML中使用元组。通常函数使用currying而不是元组来表示多个参数,但是我认为你的书还没有变成currying。 Curried函数不能像上面描述的那样使用,所以它们在这个意义上不是一般的。


I have learned (from a SML book) that functions in SML always takes just one argument: a tuple. A function that takes multiple arguments is just a function that takes one tuple as argument, implemented with a tuple binding in function binding. I understand this point.

But after this, the book says something that I don't understand:

this point makes SML language flexible and elegant design, and you can do something useful that you cannot do in Java.

Why does this design make the language Flexible? What is the text referring to, that SML can but java cannot?

解决方案

Using tuples instead of multiple arguments adds flexibility in the sense that higher-order functions can work with functions of any "arity". For example to create the list [f x, f y, f z], you can use the higher-order function map like this:

map f [x, y, z]

That's easy enough - you can do that in any language. But now let's consider the case where f actually needs two arguments. If f were a true binary function (supposing SML had such functions), we'd need a different version of map that can work with binary functions instead of unary functions (and if we'd want to use a 3-ary functions, we'd need a version for those as well). However using tuples we can just write it like this:

map f [(x,a), (y,b), (z,c)]

This will create the list [f (x,a), f (y,b), f (z,c)].

PS: It's not really true that all functions that need multiple arguments take tuples in SML. Often functions use currying, not tuples, to represent multiple arguments, but I suppose your book hasn't gotten to currying yet. Curried functions can't be used in the same way as described above, so they're not as general in that sense.

这篇关于SML:为什么函数总是采用一个参数使语言变得灵活的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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