[mercury-users] Re: Yet Another Bug: Converting List To List Of Tuples

Raphael Collet rco at missioncriticalit.com
Sat Dec 18 03:15:49 AEDT 2010


On 12/17/2010 05:02 PM, win1for at yahoo.com wrote:
> Hi Raphael,
>
> I have made the necessary changes and the code look like this. Now i
> have a new error:
>
> this is the code:
>
> ************************************************************************************
> :- module oplossing1.
>
> :- interface.
> :- import_module io.
>
> :- pred main(io.state::di, io.state::uo) is det.
>
> :- implementation.
> :- import_module int, list,string,map.
>
> :- func tabel(list(T)) = list({T,int}).

The compilation error is here:

> tabel([]) = [].
> tabel([X]) = tabel_aux([X], []).

You handle only lists with zero or one element.  You don't handle *any* 
list.  Actually tabel_aux works for any list, so you don't need to do 
pattern matching in tabel...

>
>
> :- func inc_freq(T, list({T,int})) = list({T,int}).
> inc_freq(I, []) = [{I,1}].
> inc_freq(I, [{J,N}|Freqs]) = (if (I = J)
> then [{J,N+1}|Freqs] % I's counter incremented, rest untouched
> else Freqs ++ [{J,N}] % keep J in the list, but increment the
> ). % frequency of I in Freqs

Wait, there is a mistake here above.  You don't update Freqs.  Maybe 
some recursion is needed...

>
>
> :- func tabel_aux(list(T), list({T,int})) = list({T,int}).
> tabel_aux([], FreqList) = FreqList.
> tabel_aux([X|Xs], FreqList) = inc_freq(X,FreqList) ++
> tabel_aux(Xs,FreqList).

I don't understand.  Why are you concatenating frequency lists?
inc_freq(X,FreqList) is the updated frequency list after processing X. 
You should use that one for processing the next element...

>
>
> :- func compare_freq({T,int}, {T,int}) = comparison_result.
> compare_freq({_, N1}, {_, N2}) = Result :-
> compare(Result, N1, N2).
>
> main(!IO):-
> %io.print(tabel(string.to_char_list("this is a test")),!IO),
> io.nl(!IO),
> io.print(tabel([3,2,1,2,1,1,2]),!IO),
> io.nl(!IO).
>
--------------------------------------------------------------------------
mercury-users mailing list
Post messages to:       mercury-users at csse.unimelb.edu.au
Administrative Queries: owner-mercury-users at csse.unimelb.edu.au
Subscriptions:          mercury-users-request at csse.unimelb.edu.au
--------------------------------------------------------------------------



More information about the users mailing list