Ocaml反向并映射

时间:2015-10-19 19:31:33

标签: functional-programming ocaml map-function

我有一个创建map_reverse函数的赋值。

let rec map_rev func = function
        [] -> [] 
    |   h::t -> map_rev func t @ func h;;

let f x = x * 7;;

open Printf
let a = map_rev f [1;2;10;20;400]
let () = List.iter (printf "%d ") a

现在,编译器不允许这一行:

let a = map_rev f [1;2;10;20;400]

,因为:

'This expression has type 'a * 'b but an expression was expected of type 'c -> 'd list'.

有人能指出我的错误吗?为什么期望&#c; c - >列表?

2 个答案:

答案 0 :(得分:3)

地图反转功能的类型应为('a -> 'b) -> 'a list -> 'b list。您的map_rev函数的类型为('a -> 'b list) -> 'a list -> 'b list。所以关键是弄清楚编译器认为func返回列表的原因。

答案 1 :(得分:1)

let rec map_rev func = function
        [] -> []
    |   h::t -> map_rev func t @ [func h ];;