user614287
user614287

Reputation: 271

F# making list of pairs from two lists

I need to do create a function in F# to pair elements in two lists together(See (ii) in the following picture) :enter image description here I'm actually not completely sure what the question is asking: Do I need to create a function that takes two lists and return a list of pairs where ith elements in the resulting list is a pair where first element in the pair is the ith element in the first list and second element in the pair is the ith element in the second list? I don't understand what * mean in val pairlists :'a list * 'b list -> ('a * 'b)list

If that was what I was suppose to do then here is what i tried:

let pairlists (l : 'a list) (m : 'b list) =
    if l.Length <> m.Length then 
        failwith "the two lists does not have the same size"
    else 
        [for i in 1 .. l.Length do
            yield (l.Head,m.Head)

        ]

I'm not sure how to do it as I don't know how can i iterate through the lists? Help

Upvotes: 0

Views: 2697

Answers (2)

Wote
Wote

Reputation: 116

The * in the function signature means that the input is a tuple of two lists and the output is list of tuples. Simplest way to achieve this is to use List.zip function:

let pairlists ((a, b) : 'a list * 'b list) = 
    List.zip a b

Here we define the input parameter to be tuple of 'a list and 'b list and pass the lists to List.zip : 'T1 list -> 'T2 list -> ('T1 * 'T2) list accordingly

Upvotes: 4

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

You iterate through the lists by pattern matching, which is done using the match ... with expression.

For example:

f l = 
   match l with
   | head :: tail -> "This list has at least one element!"
   | _ -> "This list is empty"

> f [1]
> "This list has at least one element!"

> f [1; 2]
> "This list has at least one element!"

> f []
> "This list is empty"

In your case, there may be several possibilities: both lists are empty, one is empty and the other is not, or both have at least one element:

pairlists l m =
    match l, m with
    | (lhead :: ltail), (mhead :: mtail) ->  // both non-empty
    | [], (mhead :: mtail) ->  // first list empty, second is not
    | (lhead :: ltail), [] ->  // second is empty, first is not
    | [], [] ->  // both are empty

Now all you need to do is decide what the result of the function should be in each one of these four cases, and then write it down.

I am not going to give you the full answer, since this is obviously homework, but here's another hint: pairing two non-empty lists means pairing their heads (i.e. first elements), then pairing their tails, then attaching the two together.

Upvotes: 3

Related Questions