# Need help on interleaving 3 lists together in OCaml

Page 1 of 1

## 2 Replies - 297 Views - Last Post: 28 October 2017 - 03:18 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=407228&amp;s=34ec883b38e982a5ecf8f45d56338810&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 SiliLo

Reputation: 0
• Posts: 1
• Joined: 28-October 17

# Need help on interleaving 3 lists together in OCaml

Posted 28 October 2017 - 07:29 AM

Hello everyone,
I have been trying to solve this interleave question for several days now and have not yet came up with a working solution. So it would be great if anyone here help me out.
This is my code here :

``` let rec interleave3 l1 l2 l3= function
| [] , [] , [] -> []
| [],  y:: ys,  z :: zs -> ["-"] :: y :: z (* if the list is empty then replace it with "-" *)
| x :: xs , [], z :: zs -> x :: ["-"] :: z
| x :: xs, y :: ys, [] -> x :: y :: ["-"]
| x :: xs, y :: ys, z :: zs ->  x :: y :: z (interleave3 xs ys zs);;

```

The result I expect is :
if l1 is [1;2;3;4], l2 is [5,6,7] and l3 is [8]
when put together it will produce =
[1;5;8;2;6; - ; 3;7; -;4;-;-]

I don't usually ask people to help me code online but I am having a really hard time getting pass this. Any suggestions will be highly appreciated.

Is This A Good Question/Topic? 0

## Replies To: Need help on interleaving 3 lists together in OCaml

### #2 baavgai

• Dreaming Coder

Reputation: 7070
• Posts: 14,746
• Joined: 16-October 07

## Re: Need help on interleaving 3 lists together in OCaml

Posted 28 October 2017 - 02:34 PM

```let rec interleave3 = function

```

or
```let rec interleave3 l1 l2 l3 =
match l1,l2,l3 with
| ...

```

I'd go with the latter.

### #3 baavgai

• Dreaming Coder

Reputation: 7070
• Posts: 14,746
• Joined: 16-October 07

## Re: Need help on interleaving 3 lists together in OCaml

Posted 28 October 2017 - 03:18 PM

Ok, there's a whole lot more at issue here.

Your hard coding of ["-"] means passing int to it is out of the question.

Not all paths are covered...

I'd write a helper function that takes a list and the filler value and returns a tuple, containing the value to use and what's left of the list. e.g.
```let split filler = function
...
# split 99 [1;2];;
- : int * int list = (1, [2])
# split 99 [2];;
- : int * int list = (2, [])
# split 99 [];;
- : int * int list = (99, [])
#

```

Quick reference:
```val split : 'a -> 'a list -> 'a * 'a list = <fun>
val interleave3 : 'a -> 'a list * 'a list * 'a list -> 'a list = <fun>
val dat : int list * int list * int list = ([1; 2; 3; 4], [5; 6; 7], [8])
val filler : int = 99
val result : int list = [1; 5; 8; 2; 6; 99; 3; 7; 99; 4; 99; 99]

```

Hope this helps.