Vladimir Chavez
Vladimir Chavez

Reputation: 79

How to compare two lists in F#

I am new to f#, so I need to do this for homework. I have been struggling now for several hours, so a hint would be appreciated it: Write a function that has the type 'a list * 'a list-> bool, where a comparison between the elements of the same index is implemented. For example: [1;2;3] and [1;2;3] are equal and [1;2;3] and [1;2;4] not.

Upvotes: 2

Views: 4137

Answers (2)

Vladimir Chavez
Vladimir Chavez

Reputation: 79

let a = [1;2;3] 
let b = [1;2;3]
let c = [1;2;5]


let rec compare xl yl = 
  match xl, yl with 
  | [], [] -> true
  | x::xs, y::ys -> x = y && compare xs ys
  | _ -> false

// compiling the code and using interactive the output is:

val a : int list = [1; 2; 3]
val b : int list = [1; 2; 3]
val c : int list = [1; 2; 5]

> 
val compare : xl:'a list -> yl:'a list -> bool when 'a : equality

> compare a b;;
val it : bool = true

> compare a c;;
val it : bool = false

Upvotes: 2

Tomas Petricek
Tomas Petricek

Reputation: 243051

Thank you for providing the useful context that this is a homework! Since this is the case, I will try to give some hint but not a fully complete working solution.

First of all, it's worth noting that you can just compare lists using = in F# and this does exactly what you need. Assuming we have some sample lists:

let l1 = [1;2;3]
let l2 = [1;2;3]
let l3 = [1;2;4]

You can do the following to compare lists:

l1 = l2 // Returns 'true'
l1 = l3 // Returns 'false'

This is probably not going to teach you much about writing F#, so I assume what you need is to write your own recursive function. This is a good exercise! There are two key tricks. First, you need a recursive function that looks at the start of the list and then calls itself recursively to process the rest of the list. Second, you'll want to use pattern matching on the two lists given as arguments. The basic structure of the function will be:

let rec compare xl yl = 
  match xl, yl with 
  | [], [] -> 
  | x::xs, y::ys -> 
  | _ -> 

Now you need to fill in the blank parts:

  • If both lists are empty. Are they equal or not?
  • If both lists are non-empty and start with x and y, followed by xs and ys.
  • Otherwise - one list is empty, the other non-empty.

Upvotes: 8

Related Questions