Monday, March 5, 2007

EOPL - 2.3.2 - Exercise 2.16

Easy one, in two versions.

Version 1

let rec list_find_last_position sym los =
match los with
[] -> None
| (s :: los') when s = sym ->
(match list_find_last_position sym los' with
None -> Some 0
| Some i -> Some (i + 1))
| (s :: los') ->
(match list_find_last_position sym los' with
None -> None
| Some i -> Some (i + 1))


Version 2

let rec list_find_last_position sym los =
match los with
[] -> None
| (s :: los') ->
match list_find_last_position sym los' with
None -> if s = sym then Some 0 else None
| Some i -> Some (i + 1)


Version 2 was obtained by observing similarities in Version 1. The idea appeared in previous examples: pattern guards do not always lead to shorter code.

1 comment:

Dylan said...

Great read thhankyou