On Wednesday, February 22, 2017 at 5:59:01 PM UTC, steenuil wrote:
>
> From what I understood, behavioural types are supposed to encode a
> program's behavior towards a resource in the type system. For example, a
> File's behavioural type could be "open -> read | write -> close", so that
> reading from a file that hasn't been opened yet, opening a file twice or
> forgetting to close a file would be a type error.
> So they can can be as useful to distributed systems as to anything else,
> really.
>
I see. The way I am handling that kind of state machine in elm is to write
state transition functions:
tryToSubmit state =
case state of
FormComplete -> Just Submit
_ -> Nothing
I think the behavioural type you have given "open -> read | write -> close"
is not corresponding exactly to a state machine - I mean one with the
states open, read, write and close. It is more describing the operations
that can be performed and the constraints between them. I think the state
machine is more like Closed (open) -> Open (read | write | close) -> Closed
What I am doing is putting the data that is needed for the operations in
type aliases, and writing 'mapWith' functions to apply a function to the
data, when in the correct state where the needed data is available. Like
this:
type alias Readable = { bytesAvailable: Int, fileHandle: Handle }
mapWhenWithReadable : (Readable -> a) -> File -> Maybe a
mapWhenWithReadable func state =
case state of
Open readable _ ->
func readable |> Just
_ ->
Nothing
Then the read operation would be something like
tryRead : Int -> File -> Maybe String
tryRead numBytes file =
mapWhenWithReadable (\readable -> ... read the data to a string) file
Then building up the state machine with the appropriate records for each
state:
type File =
Close openable
| Open readable writeable closeable
What would correspond more directly with the behavioral types, might be to
put the actual operations in the records:
type alias Read = { read : Int -> String }
I didn't do that though, in order to avoid having functions in the model.
It sounds like a pattern worth experimenting with though. I daresay some of
this research into behavioral types asks for language features beyond what
Elm has but perhaps some of its most obviously useful features can be
mapped onto patterns in Elm.
--
You received this message because you are subscribed to the Google Groups "Elm
Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.