Base64 Encoding in Elm

Our first example demonstrates base64 encoding and decoding in Elm. Here’s the full source code:

module Main exposing (main)

import Base64
import Html exposing (Html, div, text)

main : Html msg
main =
    let
        data = "abc123!?$*&()'-=@~"
        
        -- Standard base64 encoding
        sEnc = Base64.encode data
        
        -- Decoding the standard encoded string
        sDec = 
            case Base64.decode sEnc of
                Ok decodedString -> decodedString
                Err _ -> "Decoding error"
        
        -- URL-safe base64 encoding
        uEnc = Base64.encodeUrl data
        
        -- Decoding the URL-safe encoded string
        uDec = 
            case Base64.decodeUrl uEnc of
                Ok decodedString -> decodedString
                Err _ -> "Decoding error"
    in
    div []
        [ div [] [ text ("Standard encoded: " ++ sEnc) ]
        , div [] [ text ("Standard decoded: " ++ sDec) ]
        , div [] [ text ("URL-safe encoded: " ++ uEnc) ]
        , div [] [ text ("URL-safe decoded: " ++ uDec) ]
        ]

In this example, we’re using the elm/base64 package to perform base64 encoding and decoding. Let’s break down the code:

  1. We import the necessary modules: Base64 for encoding/decoding and Html for rendering the results.

  2. We define our main function, which returns an Html msg type.

  3. Inside main, we define our original data string.

  4. We use Base64.encode to perform standard base64 encoding.

  5. For decoding, we use Base64.decode. Since decoding can fail, it returns a Result type. We handle both success and error cases.

  6. We repeat the process for URL-safe encoding and decoding using Base64.encodeUrl and Base64.decodeUrl.

  7. Finally, we render the results using HTML div elements.

To run this program, you need to have Elm installed and create an Elm project with the elm/base64 package as a dependency. Then, you can compile and run the program using the Elm compiler.

The output will show both the standard and URL-safe encoded versions of the string, along with their decoded counterparts. The URL-safe version replaces + and / characters with - and _ respectively, making it safe for use in URLs.

Note that Elm’s approach to error handling is different from many other languages. Instead of using exceptions, it uses the Result type to handle potential failures in a more explicit and type-safe manner.