Methods in Standard ML

Standard ML (SML) does not have built-in support for object-oriented programming concepts like structs and methods. However, we can use records and functions to achieve similar functionality. Here’s an equivalent implementation:

(* Define a record type for rectangle *)
type rect = {width: int, height: int}

(* Function to calculate area *)
fun area ({width, height}: rect) : int =
    width * height

(* Function to calculate perimeter *)
fun perim ({width, height}: rect) : int =
    2 * width + 2 * height

(* Main function *)
fun main () =
    let
        (* Create a rectangle *)
        val r = {width = 10, height = 5}
        
        (* Call the functions *)
        val _ = print ("area: " ^ Int.toString (area r) ^ "\n")
        val _ = print ("perim: " ^ Int.toString (perim r) ^ "\n")
        
        (* In SML, we don't need to create a pointer equivalent *)
        (* The following calls would be identical to the above *)
        val _ = print ("area: " ^ Int.toString (area r) ^ "\n")
        val _ = print ("perim: " ^ Int.toString (perim r) ^ "\n")
    in
        ()
    end

(* Execute the main function *)
val _ = main()

In this Standard ML implementation:

  1. We define a rect type using a record, which is similar to a struct.

  2. Instead of methods, we define separate functions area and perim that take a rect as an argument.

  3. In the main function, we create a rectangle and call our functions.

  4. Standard ML doesn’t have the concept of pointers in the same way as some other languages. All values are implicitly passed by reference, so we don’t need to create a separate pointer example.

  5. We use print and Int.toString for output, as Standard ML doesn’t have a direct equivalent to fmt.Println.

To run this program, you would typically save it in a file with a .sml extension (e.g., rectangle.sml) and then use an SML interpreter or compiler. For example, if you’re using Standard ML of New Jersey (SML/NJ), you could run:

$ sml rectangle.sml
area: 50
perim: 30
area: 50
perim: 30

Note that Standard ML is a functional programming language, so the approach here is more functional than object-oriented. The concept of methods attached to structs doesn’t exist in the same way, but we can achieve similar functionality using records and functions.