Skip to content

Instantly share code, notes, and snippets.

@fliedonion
Last active November 7, 2017 04:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fliedonion/fd846e12ef19846934364288fc922073 to your computer and use it in GitHub Desktop.
Save fliedonion/fd846e12ef19846934364288fc922073 to your computer and use it in GitHub Desktop.
hello-elm
import Html exposing (text, h1)
{-
type alias EmailAddress = String
type alias Message =
{ recipient : EmailAddress
, body : String
}
message : Message
message = { recipient = "Hello", body = "hello" }
-}
-- ofcource not all strings are valid email address.
-- UnionType version
type EmailAddress = EmailAddress String
type alias Message =
{ recipient : EmailAddress
, body : String
}
message : Message
message = { recipient = EmailAddress "Hello"
, body = "hello" }
validateAddress : String -> Result String EmailAddress
validateAddress s =
if String.contains "@" s
then Result.Ok (EmailAddress s)
else Result.Err "not a valid emailaddress"
data : String
data = "hello@example.com"
emailToString : EmailAddress -> String
emailToString (EmailAddress s) = s
main =
let content =
data
|> validateAddress
|> Result.map emailToString
|> Result.withDefault "invalid"
in h1 [] [text content]
import Html exposing (text)
type alias Person =
{ name: String
, age : Int
, occupation : String
, salary : Float
, dog : Dog
}
type alias Dog =
{ name : String
, breed : String
, sterilized : Bool
}
joe : Person
joe =
{ name = "Joe"
, age = 21
, occupation = "Analyst"
, salary = 10000
, dog = fido
}
promote : Person -> Person
promote p =
{ p | occupation = "Manager"
, salary = p.salary * 1.2 }
sterilizePet : Person -> Person
sterilizePet p =
let
dog = p.dog
in
{ p | dog = { dog | sterilized = True } }
{-
-- can't do that ( you can't reference p.dog inside this nested record )
sterilizePet p =
{ p | dog = { p.dog | sterilized = True } }
-}
fido : Dog
fido = { name = "Fido"
, breed = "Husky"
, sterilized = False }
greet : Person -> String
greet r = "Hello " ++ r.name
main =
joe |> promote |> sterilizePet |> toString |> text
-- text (toString (promote joe))
main =
text
((l1 |> List.head |> unwrapMaybe |> toString)
++ (l2 |> List.head |> unwrapMaybe |> toString)
++ (l3 |> List.head |> unwrapMaybe |> toString)
)
unwrapMaybe : Maybe number -> number
unwrapMaybe p1 = case p1 of
Nothing -> 0
Just a -> a
l1 : List Float
l1 = [1.2]
l2 : List Int
l2 = [1,2,3]
l3 : List Int
l3 = []
main = v |> resolve |> toString |> text
v : Result String Int
v = String.toInt "190"
resolve : Result String Int -> Int
resolve p1 = case p1 of
Ok val -> val
Err s -> 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment