4 ms·
The fact list_length([], 0) says "the length of an empty list [] is 0". The clause says "the length of the list [_|Ls] (i.e, any element concat Ls) has length N
by tomdre 10y ago
The fact list_length([], 0) says "the length of an empty list [] is 0". The clause says "the length of the list [_|Ls] (i.e, any element concat Ls) has length N if N>0, N=N0+1, and the length of Ls is N0". Hope this helps.
- FabHK 10y agoWhy do you have to specify that N>0? Seems to me that this ought to be sufficient: the list [_|Ls] has length N if N=N0+1, and the length of Ls is N0
- tom_mellior 10y agoIn this particular example, specifying that N > 0 helps with running the predicate "backwards": You can use the query "length(L, 3)" to enumerate "all" lists of length 3, for example: ?- length(L, 3). L = [_G926, _G929, _G932]. This is not particularly informative for beginners, but it's a list containing exactly three distinct logic variables. Any three-element list is an instance of this. When running in this mode, the N #> 0 constraint ensures termination; otherwise, the recursive clause would find the three-element list, but then continue a futile infinite search for further lists (of negative length, which cannot exist). It takes a bit of getting used to Prolog's execution model to really understand why this is the case.
- FabHK 10y agoThanks for the informative reply. A related observation, by the way, regarding programming languages: often it all sort of makes sense, and you can put stuff together that gets you the correct result without really knowing what's actually going on behind the scenes. However, when you need stuff to go fast, then you really need to know the underlying runtime, execution model, memory model, etc. to find the incantation that's not only right, but efficient.