Search code examples
searchprologtrace

Prolog graph search


I have created a simple graph search from an example

move(math101, math102).
move(math101, chem101).
move(math102, math210).
move(math102, phys102).
move(phys102, phys201).
move(math210, phys201).


search(A, A, [A]).

search(A, B, [A|Path]) :-
        move(A,C),
        search(C,B,Path).

I can tell you that to get to 'phys201' from 'math101' you need to pass through 'math102' and 'math210' or 'math102' and'phys102'

I am trying to prove this in prolog but its not working, I think it may have something to do with the query i am typing

search(math101,phys201,[math101])

Or is it something in my code, I have traced the path and it keeps binning out with a No result

The trace is

[1]CALL:  search(math101, phys201, [math101])
[1]FOUND: search(_4193470, _15353627, [_4193470|_14830180]):-move(_4193470, _8522358),            search(_8522358, _15353627, _14830180).
[1]BIND:  search(math101, phys201, [math101])
[2]CALL:  move(math101, _10259988)
[2]FOUND: move(math101, math102).
[2]BIND:  move(math101, math102)
[3]CALL:  search(math102, phys201, [])
[3]FAIL:  search(math102, phys201, [])
[2]REDO:  move(math101, math102)
[4]CALL:  move(math101, _10259988)
[4]FOUND: move(math101, chem101).
[4]BIND:  move(math101, chem101)
[5]CALL:  search(chem101, phys201, [])
[5]FAIL:  search(chem101, phys201, [])
[4]REDO:  move(math101, chem101)
[6]CALL:  move(math101, _10259988)
[6]FAIL:  move(math101, _10259988)
[1]REDO:  search(math101, phys201, [math101])

Please help


Solution

  • as you suppose, your query is the problem: try

    ?- search(math101,phys201,X).
    X = [math101, math102, math210, phys201] ;
    X = [math101, math102, phys102, phys201] ;
    false.
    

    or, with some more instantiated path

    ?- search(math101,phys201,[math101|X]).
    X = [math102, math210, phys201] ;
    X = [math102, phys102, phys201] ;
    false.