Strings and Runes in Elm

module Main exposing (main)

import Html exposing (Html, div, text)


main : Html msg
main =
    div []
        [ text "สวัสดี"
        , text (String.fromInt (String.length "สวัสดี"))
        , text (String.join " " (List.map (String.fromInt << Char.toCode) (String.toList "สวัสดี")))
        , text (String.fromInt (String.length "สวัสดี"))
        , div [] (List.map viewChar (String.toList "สวัสดี"))
        ]


viewChar : Char -> Html msg
viewChar char =
    div []
        [ text (String.fromChar char)
        , text " "
        , text (String.fromInt (Char.toCode char))
        ]

In Elm, strings are UTF-8 encoded, similar to many other languages. However, Elm doesn’t have a direct equivalent to Go’s concept of runes. Instead, we work with Char types, which represent Unicode code points.

Let’s break down the code:

  1. We define a constant string "สวัสดี", which is “hello” in Thai.

  2. We use String.length to get the length of the string. This gives us the number of Unicode code points, not the number of bytes.

  3. We convert the string to a list of characters using String.toList, then map over this list to convert each character to its Unicode code point using Char.toCode. We then join these numbers into a string for display.

  4. We again display the length of the string, which will be the same as before.

  5. We create a list of div elements, each containing a character from our string along with its Unicode code point.

  6. The viewChar function is used to create the view for each character. It displays the character itself and its Unicode code point.

In Elm, we don’t have the same low-level access to the byte representation of strings as we do in Go. Elm abstracts away these details, working at the level of Unicode code points instead.

Also, Elm doesn’t have a direct equivalent to Go’s range loop for strings. Instead, we typically use functions like String.toList to convert a string to a list of characters, which we can then process using Elm’s list functions.

To run this Elm code, you would typically compile it to JavaScript and run it in a web browser. The output would be displayed as HTML elements on the page, rather than as console output.