标准 ML:返回不同类型
我需要根据传递到另一个函数的函数返回不同的值。
因此,鉴于:
fun inc x = x + 1;
并且:
fun double([]) = []
| double(h::t) = 2 * h :: double(t);
您应该能够调用我正在使用的函数。
示例调用(我正在创建的函数名为 test):
test (inc, 5);
- 它将返回 6
-OR-
test (double , [1,2,3,4]);
- 它会返回 [2,4,6,8]
我知道函数不能从表面上做到这一点,但这可以通过抽象层实现吗?
I need to return a different value based on the function passed into another function.
So, given:
fun inc x = x + 1;
And:
fun double([]) = []
| double(h::t) = 2 * h :: double(t);
You should be able to call the function I'm working on with either.
Example call (the function I'm making is named test):
test (inc, 5);
- And it would return 6
-OR-
test (double, [1,2,3,4]);
- And it would return [2,4,6,8]
I know that functions can't do this at face value, but is this possible through layers of abstraction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然,这是可能的:
test
现在的类型为(('a -> 'b) * 'a) -> 'b
,这意味着如果您传入一个返回 int 的函数(例如inc
),则结果将是一个 int,如果您传入一个返回列表的函数,结果将是一个列表。作为旁注: double 可以更容易/更惯用地定义为 fun double xs = map (fn x -> x*2) xs 或 val double = 地图(fn x -> x*2)。
Sure, that's possible:
test
now has the type(('a -> 'b) * 'a) -> 'b
, which means that if you pass in a function that returns an int (likeinc
), the result will be an int and if you pass in a function that returns a list, the result will be a list.As a sidenote:
double
could be more easily/idiomatically be defined asfun double xs = map (fn x -> x*2) xs
orval double = map (fn x -> x*2)
.