列表上的广义映射和过滤器操作- ML



我一直在尝试创建一个ML函数(柯里化),它从形式(谓词,函数)和列表中获取元组列表,并返回返回true的每个元素的函数操作,即对于每个条件都有一定的函数要执行,例如:

    - map_many [(fn x => x mod 2 = 0, fn x => x*2), (fn x => x mod 3 = 0, fn x => x+5), (fn x => x mod 4 = 0, fn x => x*x)] [1,2,3,4,5,6,7,8,9,10];
val it = [1,4,8,64,5,17,7,256,14,20] : int list

这就是我一直在尝试做的,但它不太好:

fun map_many _ [] = []
  | map_many [] _ = []
  | map_many ((y,z)::ys) (x::xs) =
    if (y(x) = true)
        then z(x)::map_many ys xs
    else
        x::map_many ys xs; 

我做错了什么?

这将给出您想要的输出。

fun map_one [] (old,x) = x
  | map_one ((p,f)::fs) (old,x) = 
      if p old
      then map_one fs (old,(f x))
      else map_one fs (old,x)
fun map_many _ [] = []
  | map_many fs (x::xs) = map_one fs (x,x) :: map_many fs xs

注意,map_one使用元组int*int来跟踪旧值(您在谓词中使用的值)和生成的值。


你的代码只使用了每对函数一次,每个数字一次。你总是把ysxs放入递归函数中,以相同的速率运行它们,而不是运行第一个,在第二个上向下移动一次,然后再运行第一个。当您想执行length(ys)*length(xs)时,您正在执行max(length(ys),length(xs))操作。

最新更新