The IO err ok
type is very similar in concept to Task err ok
. The first parameter is the error
value, the second value is the "return" value of an IO-operation.
A program must have the type IO String ()
. The error parameter must have type String
.
This allows the runtime to print error message to std err in case of a problem.
Sleep process execution in milliseconds.
Exit to shell with a status code
Applicative
map2 : (a -> b -> c) -> IO x a -> IO x b -> IO x c
map2 fn a b =
IO.return fn
|> IO.andMap a
|> IO.andMap b
Instead of:
sleep 100
|> andThen (\_ -> printLn "Hello")
and
allows you to do:
sleep 100
|> and (printLn "Hello")
Perform a task
getTime : IO x Time.Posix
getTime =
performTask Time.now
Attempt a Task that can fail.
For example you can fetch data using the elm/http package.
import Http
fetch : IO String String
fetch =
Http.riskyTask
{ method = "GET"
, headers = []
, url = "http://example.com"
, body = Http.emptyBody
, resolver = Http.stringResolver stringBody
, timeout = Just 10
}
|> attemptTask
stringBody : Http.Response String -> Result String String
stringBody response =
case response of
Http.GoodStatus_ metaData body ->
Ok body
_ ->
Err "Problem"
Call a synchronous function in Javascript land.
This works by sending out a message through a port. The Javascript implementation will then send the return value back through another port.
callJs <fn> <args> <result decoder>
js/my-functions.js
module.exports = {
addOne: function(num) {
// sync example
return num + 1;
},
sleep: function(delay) {
// async example
return new Promise(resolve => {
setTimeout(resolve, delay);
});
},
}
src/MyModule.elm
addOne : Int -> IO x Int
addOne n =
IO.callJs
"addOne"
[ Encode.int n
]
Decode.int
sleep : Float -> IO x ()
sleep delay =
IO.callJs
"sleep"
[ Encode.float delay
]
(Decode.succeed ())
Run like this:
elm.cli run --ext js/my-functions.js src/MyModule.elm
Used by elm-cli
to wrap your program.
Create your own program by defining program
in your module.
program : Process -> IO String ()
program process =
printLn "Hello, world!"