Following code snippet shows how to compute bound (i.e the min and max elements) of a List using F#.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let rec bound (lst:int list) : (int*int) option = | |
match lst with | |
| [] -> None // Empty List | |
| xhd::xtl -> | |
match bound xtl with | |
| None -> Some (xhd,xhd) // List with only 1 element | |
| Some (x,y) -> | |
Some ((if x>xhd then xhd else x), (if y<xhd then xhd else y)) | |
Solution outlined here is quite trivial and use the pattern matching facilities of F#. In case of an empty list (line 3), it returns None
; otherwise, it returns the bound as Some (int*int)
(line 8).
Therefore, the signature of bound
is given by-
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val bound : lst:int list -> (int * int) option |
Output of bound
–
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> bound [1;2;3;4];; | |
val it : (int * int) option = Some (1, 4) | |
> bound [1];; | |
val it : (int * int) option = Some (1, 1) | |
> bound [];; | |
val it : (int * int) option = None |