I need to make a function that takes two lazy list and an operator and applies this operator to elements of the same index on the lazy list. For example, [1; 2; 3], [2; 3; 4; 5] + will return [3; 5; 7; 5]. Lazy list is recorded as normal for readability.

Here is my code, an error occurs in it after function () ->, This expression has the type int lazyList * int lazyList * char -> int

type 'a lazyList = LNil | LCons of 'a * (unit -> 'a lazyList);; let rec ldzialanie listA listB operator = function | LCons(xA, xfA), LCons(xB, xfB), '+' -> LCons(xA + xB, function() -> ldzialanie xfA xfB '+') | LCons(xA, xfA), LCons(xB, xfB), '-' -> LCons(xA - xB, function() -> ldzialanie xfA xfB '-') | LCons(xA, xfA), LCons(xB, xfB), '/' -> LCons(xA / xB, function() -> ldzialanie xfA xfB '/') | LCons(xA, xfA), LCons(xB, xfB), '*' -> LCons(xA * xB, function() -> ldzialanie xfA xfB '*') | LNil, LNil, _ -> LNil | LNil, LCons(x, xf), _ -> LCons(x, function() -> xf()) | LCons(x, xf), LNil, _ -> LCons(x, function() -> xf()) | LCons(_), LCons(_), _ -> failwith "Not existible operator" ;; 

    1 answer 1

    A little weird you implement it, but somehow

     type 'a lazyList = | LCons of 'a * (unit -> 'a lazyList) | LNil let rec ldzialanie listA listB operator = match (listA, listB) with | LCons(xA, xfA), LCons(xB, xfB) -> LCons(operator xA xB, function () -> ldzialanie (xfA ()) (xfB ()) operator) | LCons(x, xf), LNil -> LCons(x, xf) | LNil, LCons(x, xf) -> LCons(x, xf) | LNil, LNil -> LNil let print list = let rec print_rec = function | LCons (a, xf) -> Printf.printf "%d " a; print_rec (xf ()) | LNil -> () in print_rec list ; print_newline () 

    Corrected your code, besides, made the operator a function of 'a -> 'a -> 'a , and not a symbol, which restricts it to work only with lazy lists of integers. Added the print function, which works only with lists of integers, but it doesn’t belong to the task, it is provided only for debugging, so I did it for simplicity.

    Usage example

     # let a = LCons (1, fun () -> LCons (2, fun () -> LCons (3, fun () -> LNil))) ;; # let b = LCons (2, fun () -> LCons (3, fun () -> LCons (4, fun () -> LCons (5, fun () -> LNil)))) ;; # print a ;; 1 2 3 - : unit = () # print b ;; 2 3 4 5 - : unit = () # print (ldzialanie ab (+)) ;; 3 5 7 5 - : unit = ()