OCaml: Combining List Items, Functional Reasoning

I went back to coding in OCaml and I missed it so much. I missed it so that I completely lost my reasoning in this language, and today I hit the wall.

What I want to do is a combination of elements between a set of n lists. I decomposed the problem by first trying to merge the elements between two lists of arbitrary sizes.

Suppose we have lists: l1 = [1;2;3]and l2 = [10,20].

What I want to do is get the following list:

 l_res = [10;20;20;40;30;60]

I know how to do this using loop structures, but I really want to solve this without them.

I tried the following:

       let f l1 l2 = 
         List.map (fun y -> (List.map (fun x -> x * y) l1) l2

But this does not seem to work. The type that I get is f : int list -> int list -> int list list, but I wantf : int list -> int list -> int list

I have tried many different approaches already, I feel that I am complicating.

What did I miss?

+4
3

, , List.map f [a; b; c] [f a; f b; f c], ,

f [a; b; c] [d; e] = [[ad; ae]; [bd; be]; [cd; ce]]

 f [a; b; c] [d; e] = [ad; ae; bd; be; cd; ce]

, :

 let f l1 l2 = 
   let res = List.fold_left (fun acc x ->
     List.fold_left (fun acc y -> (x * y) :: acc) acc l2
   ) [] l1 in
   List.rev res

:

val concat : 'a list list -> 'a list

. - ( ), . tail-recursive ( + -).

 val flatten : 'a list list -> 'a list

, concat. - ( + ).

+4

Core -flavoured :

open Core.Std

let f1 l1 l2 =
  List.map (List.cartesian_product l1 l2) ~f:(fun (x, y) -> x * y)

let f2 l1 l2 =
  List.concat_map l1 ~f:(fun x -> List.map l2 ~f:(fun y -> x * y))

let f4 l1 l2 =
  let open List.Monad_infix in
  l1 >>= fun x ->
  l2 >>| fun y ->
  x * y

(, , ) , . Batteries, , , , , () monads.

+2
let f l1 l2 =  
  let multiply x = List.map (( * )x) l2 in
  l1 |> List.map multiply
     |> List.concat
+1
source

Source: https://habr.com/ru/post/1652500/


All Articles