Struct Embedding in Elm
Elm supports composition of types through a concept similar to struct embedding. This is achieved through the use of extensible records and type aliases.
```elm
module Main exposing (main)
import Html exposing (Html, div, text)
type alias Base =
{ num : Int }
describe : Base -> String
describe base =
"base with num=" ++ String.fromInt base.num
type alias Container =
{ base : Base
, str : String
}
main : Html msg
main =
let
co =
{ base = { num = 1 }
, str = "some name"
}
in
div []
[ text ("co={num: " ++ String.fromInt co.base.num ++ ", str: " ++ co.str ++ "}")
, Html.br [] []
, text ("also num: " ++ String.fromInt co.base.num)
, Html.br [] []
, text ("describe: " ++ describe co.base)
, Html.br [] []
, text ("describer: " ++ describe co.base)
]In Elm, we don’t have struct embedding as in some other languages, but we can achieve similar composition using record types and type aliases.
We define a Base type alias with a num field, and a describe function that works with Base values.
The Container type alias includes a base field of type Base, along with an additional str field. This is similar to embedding in other languages.
In the main function, we create a Container value. We can access the num field through co.base.num.
Elm doesn’t have method-like syntax, so we call the describe function by passing co.base as an argument.
Elm uses a more functional approach to polymorphism, so we don’t need to explicitly define interfaces. The describe function can work with any record that has a num field.
To run this Elm program, you would typically compile it to JavaScript and run it in a web browser. The output would be displayed on the web page.