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

Volker Wysk post at volker-wysk.de
Sat Oct 15 20:06:00 AEDT 2022


Am Samstag, dem 15.10.2022 um 14:14 +0530 schrieb Razetime:
> 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.
> _______________________________________________
> users mailing list
> users at lists.mercurylang.org
> https://lists.mercurylang.org/listinfo/users

This is your turn/3 predicate:

:- pred turn(int::in, dir::in, int::out) is det.

This is foldl:

:- pred foldl(pred(L, A, A), list(L), A, A).

You have switched the first two arguments in the declaration and definition
of turn/3.

Volker
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: This is a digitally signed message part
URL: <http://lists.mercurylang.org/archives/users/attachments/20221015/8391500b/attachment.sig>


More information about the users mailing list