简体   繁体   English

SML 函数和元组

[英]SML Function and Tuples

The SML function map takes a function and a list and it applies the function on the elements of the list. SML 函数映射接受一个函数和一个列表,并将该函数应用于列表的元素。

The function map, which has the following type, is both polymorphic and higher order function.具有以下类型的函数映射既是多态函数又是高阶函数。

fun map f [] = [] | map f (x::xs) = (f x)::(map f xs) 
val it = fn : (’a -> ’b) -> ’a list -> ’b list

Write another function mymap that takes two functions f and g and a list of 2-element tuples.编写另一个函数 mymap,它接受两个函数 f 和 g 以及一个 2 元素元组列表。

It applies f on the first element of the tuples and it applies g on the second element of the tuples.它将 f 应用于元组的第一个元素,并将 g 应用于元组的第二个元素。

For example:例如:

- fun sqr x = x* x;
val sqr = fn : int -> int
- fun cube x:real = x*x*x;
val cube = fn : real -> real
- mymap sqr cube [(1,2.0),(2,3.0),(3,4.0),(4,5.0)];

I don't know how to used first function map and i need hint for second function mymap我不知道如何使用第一个函数映射,我需要第二个函数 mymap 的提示

You could try:你可以试试:

fun mymap f g l =
    let 
       fun  f1 f (h,h1) = (f(h),h1)

       fun  g1 g (h,h1) = (h,g(h1))
    in
        map (g1 g) (map (f1 f) l)
    end

We define two functions f1,g1 which have tuple as argument so that we could use map with f1 and list of tuples and same for g1.我们定义了两个函数 f1,g1,它们以元组作为参数,以便我们可以使用带有 f1 的映射和元组列表,而 g1 也是如此。

Example:例子:

- mymap sqr sqr [(4,9),(4,16),(9,4)];
val it = [(16,81),(16,256),(81,16)] : (int * int) list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM