CSE 130 Spring 2011 - Style Exercise 1



Problem 1

Consider the following function has_one_element that attempts to take a list as input and return true if its length is exactly one and false otherwise.

let has_one_element_a l =
if List.tl l = []
then true
else false

This code has a bug, however, and might fail with a runtime exception when certain lists are provided as input. Briefly describe the problem.

Problem 2

Here are four other versions of the above function. Briefly explain how each improves upon the previous version. Or if you think a version is inferior to the one before, explain why.

Hint: variants A and B may also fail at runtime.

Variant A

let has_one_element l =
List.tl l = []

Variant B

let has_one_element l =
match l with
| x::[] -> true

Variant C

let has_one_element l =
match l with
| [] -> false
| x::[] -> true
| h::t -> false

Variant D

let has_one_element l =
match l with
| [_] -> true
| _ -> false

Problem 3

Based on the style used in variant D, implement the following function that returns true if its input list has length two and false otherwise.

val has_two_elements : 'a list -> bool