[m-users.] [Beginner] Fixing a type error in parameter of foldl

Razetime rraghu.11502 at gmail.com
Sat Oct 15 19:44:07 AEDT 2022


This is my program (spoilers for advent of code 2016 day 2):

:- module a02.

:- interface.
:- import_module io.
:- pred main(io::di,io::uo) is det.
:- type dir ---> u;d;l;r.

:- implementation.
:- import_module int,string,list,require.

:- pred p1(list(dir)::in,int::in,int::out) is det.
p1(D,S,F):-foldl(turn,D,S,F).

:- pred turn(int::in,dir::in,int::out) is det.
turn(S,l,E):-if S rem 3=0 then E=S else E=S-1.
turn(S,r,E):-if S rem 3=2 then E=S else E=S+1.
turn(S,u,E):-if S//3=0 then E=S else E=S-3.
turn(S,d,E):-if S//3=2 then E=S else E=S+3.

:- pred char_dir(character::in,dir::out) is det.
char_dir('U',u).
char_dir('D',d).
char_dir('L',l).
char_dir('R',r).
char_dir(_,_):-unexpected($pred,"'dir").

main(!IO):-
  read_named_file_as_lines("inp/02",I,!IO),
  (I=ok(L);
  I=error(E),print(E,!IO),L=[]),
  map((pred(X::in,Y::out) is det:-
         string.to_char_list(X,Y0),
         map(char_dir,Y0,Y)),L,Lc),
  print(Lc,!IO),
  nl(!IO).

The error I get is the following:

a02.m:012: In clause for predicate `p1'/3:
a02.m:012:   in argument 1 of call to predicate `foldl'/4:
a02.m:012:   type error: type of argument does not match its expected type;
a02.m:012:   argument has overloaded actual/expected types {
a02.m:012:     (expected) `pred(
a02.m:012:       L,
a02.m:012:       A,
a02.m:012:       A
a02.m:012:     )',
a02.m:012:     (expected) `pred(
a02.m:012:       character,
a02.m:012:       A,
a02.m:012:       A
a02.m:012:     )',
a02.m:012:     (inferred) `pred(
a02.m:012:       int,
a02.m:012:       a02.dir,
a02.m:012:       int
a02.m:012:     )',
a02.m:012:     (inferred) `pred(
a02.m:012:       int,
a02.m:012:       a02.dir,
a02.m:012:       int
a02.m:012:     )'
a02.m:012:   }.
For more information, recompile with `-E'.

however, the types of this predicate 'turn' do not coincide with the
types for foldl and I do not understand why. I do not understand why
the character type is expected in the first slot.


More information about the users mailing list