2 Replies - 244 Views - Last Post: 28 October 2017 - 03:18 PM Rate Topic: -----

#1 SiliLo  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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  Icon User is offline

  • Dreaming Coder
  • member icon


Reputation: 6979
  • View blog
  • Posts: 14,605
  • Joined: 16-October 07

Re: Need help on interleaving 3 lists together in OCaml

Posted 28 October 2017 - 02:34 PM

Your sig looks wrong. Your two logical options are:
let rec interleave3 = function


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



I'd go with the latter.
Was This Post Helpful? 0
  • +
  • -

#3 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon


Reputation: 6979
  • View blog
  • Posts: 14,605
  • 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.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1