Last active
April 20, 2020 17:03
-
-
Save eatonphil/eedb27ad471d1c0c5336bab785b57c81 to your computer and use it in GitHub Desktop.
Simple functor example in Standard ML
This file contains hidden or 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
| (* | |
| * $ polyc list.sml | |
| * $ ./a.out | |
| * 2 | |
| * 2 | |
| *) | |
| signature LIST = | |
| sig | |
| type t | |
| type element | |
| val indexOf : (t * element * int) -> int | |
| end | |
| signature LIST_DOMAIN = | |
| sig | |
| eqtype t | |
| end | |
| functor List (D: LIST_DOMAIN) : LIST where type element = D.t = | |
| struct | |
| type element = D.t | |
| type t = element list | |
| fun indexOf (l: t, e: element, start: int) : int = | |
| case l of | |
| [] => ~1 | |
| | (head :: tail) => | |
| case head = e of | |
| true => start | |
| | false => indexOf (tail, e, start + 1) | |
| end | |
| structure StringT = | |
| struct | |
| type t = String.string | |
| end | |
| structure IntT = | |
| struct | |
| type t = Int.int | |
| end | |
| structure StringList = List (StringT) | |
| structure IntList = List (IntT) | |
| fun main () = | |
| let | |
| val i = StringList.indexOf (["foo", "bar", "car"], "car", 0) | |
| val j = IntList.indexOf ([1, 2, 5, 7], 5, 0) | |
| in | |
| PolyML.print (i); | |
| PolyML.print (j); | |
| () | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment