-1
let rec intmult =
  fun (aList ,al) ->
    if(List.tl aList == []) then
      ((List.hd aList) *  al)   
    else
      List.hd aList * al :: intmult (List.tl aList , al);; 

为什么是错的?

4

2 回答 2

2

你的两个分支if返回不同的类型。第一个分支返回一个int. 第二个 ( else) 分支返回一个整数列表。OCaml 表达式必须具有单一类型,因此您需要以某种方式使这两种类型相同。

我也有点担心如果你将一个空列表传递给这个函数会发生什么。

于 2013-04-01T06:46:44.650 回答
1

这可能是一种更好的写法:

let rec intmult : int list * int -> int list =
   function ([],_) -> [0]   (* this case is not processed by your code *)
   |  ([x] ,al) -> [x * al]    (* this case returns an int in your code *)
   | (x::xs,al) ->  x * al :: intmult (xs, al);; 

你也可以使用List.map

let intmult (l,m)= List.map (fun x -> x * m) l
于 2013-04-01T10:12:56.820 回答