Search code examples
haskellprolog

Converting a Prolog program to a Haskell program


I've got this review question for one of my exams, and I need some guidance.

Using the following Prolog program as an executable specification,

mix(Xs,Ys):-remix(Xs,[],Ys).

remix([],Ys,Ys).    
remix([X|Xs],Ys,Zs):-remix(Xs,[X|Ys],Zs).

write an equivalent Haskell program.

This is what I have so far for the Haskell code:

mix Xs Ys = remix Xs [] Ys

remix [] Ys Zs = Zs

remix (X:Xs) Ys Zs = x : (remix Xs Ys Zs)

Is this Haskell program be equivalent to the Prolog code above? If not, what am I doing wrong?


Solution

  • The literal translation would be:

    mix xs = remix xs []
    remix [] ys = ys
    remix (x:xs) ys = remix xs (x:ys)
    

    Assuming that the first argument to mix/2 is strictly an input argument, and the last argument of both mix/2 and remix/3 are output argument. Then, the Haskell functions have as a return value the last argument of the Prolog predicates you are translating. Otherwise, the Haskell version is exactly the same as the Prolog, just correct Haskell syntax. Compare it to your attempt and you will see a lot of small differences (and I guess the Haskell compiler would tell you about these too?)

    (Haskellers please correct me if this is wrong)

    There are however some issues with this. The original Prolog program could be queried both ways:

    ?- mix([1,2,3], M).
    M = [3, 2, 1].
    
    ?- mix(M, [3,2,1]).
    M = [1, 2, 3] .
    

    or even:

    ?- mix(X, Y), numbervars(X-Y, 0, _).
    X = Y, Y = [] ;
    X = Y, Y = [A] ;
    X = [A, B],
    Y = [B, A] ;
    X = [A, B, C],
    Y = [C, B, A] ;
    X = [A, B, C, D],
    Y = [D, C, B, A] . % and so on
    

    However, the second query leaves a choice point, and if you try to see what other solutions you might get (type Space or ; instead of Enter), the program does not terminate. Does it say how the original Prolog program is meant to be used?