To reverse a list, it isn't important what type the list elements are, only what order they're in. This is a perfect candidate for a generic function, so the same reverseal function can be used no matter what list is passed.
let rev list =
let rec loop acc = function
| [] -> acc
| head :: tail -> loop (head :: acc) tail
loop [] list
The code makes no assumptions about the types of the elements. The compiler (or F# interactive) will tell you that the type signature of this function is 'T list -> 'T list
. The 'T
tells you that it's a generic type with no constraints. You may also see 'a
instead of 'T
- the letter is unimportant because it's only a generic placeholder. We can pass an int list
or a string list
, and both will work successfully, returning an int list
or a string list
respectively.
For example, in F# interactive:
> let rev list = ...
val it : 'T list -> 'T list
> rev [1; 2; 3; 4];;
val it : int list = [4; 3; 2; 1]
> rev ["one", "two", "three"];;
val it : string list = ["three", "two", "one"]