[m-users.] Instantiatedness and handling io results

Philip White philipwhite at cedarville.edu
Sun Aug 4 17:48:33 AEST 2019


I'm trying to get a little momentum in understanding how one actually
writes programs with mercury. Coming from the Haskell and Ocaml world,
I'm pleased by the static checks that are possible with mercury, but a
lot of the syntax and some other choices make me think that mercury is
prone to a lot of boilerplate. I'd like to be proven wrong, so I'm going
to try to use it, make mistakes, and then hopefully learn from those
mistakes.

Below is a program that should read in two ints from stdin, and print
all the numbers between. Nothing two complicated.

```
main(!IO) :- 
  read_word(FirstResult, !IO),
  read_word(SecondResult, !IO),
  ( FirstResult = ok(FirstDieString)
  , ( SecondResult = ok(SecondDieString)
    , string.to_int(string.from_char_list(FirstDieString), FirstDie)
    , string.to_int(string.from_char_list(SecondDieString), SecondDie)
    ,  foldl(io.write_int, (FirstDie .. SecondDie), !IO)
    ; error("Bad second read") )
  ; error("Bad read") ).
```

Sadly, I'm getting this compilation error.

```
In clause for `main(di, uo)': in call to predicate `list.foldl'/4: mode
error: arguments `TypeCtorInfo_24, TypeCtorInfo_25, V_18, V_19,
STATE_VARIABLE_IO_13, STATE_VARIABLE_IO' have the following insts:
unique(<type_ctor_info for .int/0>), unique(<type_ctor_info for
io.state/0>), /* unique */(pred((ground >> ground), (unique >>
clobbered), (free >> unique)) is det), ground, mostly_unique, free which
does not match any of the modes for predicate `list.foldl'/4.
```

Due to another error I got from a previous attempt, my guess is that
this has to do with this program attempting to do backtracking if
`FirstResult` is not `ok`, which then makes the inst of `!IO` be
inferred as `mostly_unique` instead of `unique`.

Two questions:
1. How do I make this program type check?
2. What is the idiomatic way of handling a sequence of things which
return results? In Haskell, there is do-notation for sequencing monads,
but I haven't seen any monads in mercury.


More information about the users mailing list