Ocaml List元素乘法

时间:2013-04-01 06:36:46

标签: ocaml

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);; 

为什么错了?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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
相关问题