When to use phrase in Prolog?
Asked Answered
C

2

5

I'm trying to learn more about DCGs in Prolog and while reading through different sources, I noticed that in some cases phrase wasn't being used ?

From the Learn Prolog Now website, it presents this example:

s   -->  np,vp. 
np  -->  det,n. 
vp  -->  v,np. 
vp  -->  v. 
det -->  [the]. 
det -->  [a]. 
n   -->  [woman]. 
n   -->  [man]. 
v   -->  [shoots].

They then use the query s(X,[]) to generate all the sentences in the grammar. I tried phrase(s,L) and it also generates all the sentences described by the grammar.

What's the difference in using s(X,[]) and phrase(s,L)? When should phrase be used?

Checky answered 3/12, 2015 at 21:33 Comment(1)
You mean s(X, []) not s([], X). The query s([], X) will fail. :)Geostrophic
B
3

Grammar rules should always be accessed using the phrase/2-3 predicates. When the first argument is instantiated, the Prolog compiler should be expected to convert the phrase/2-3 call to a call to the predicate generated by the compilation of called grammar rule. Thus, there should be no overhead by using the phrase/2-3 predicates.

Basset answered 3/12, 2015 at 22:24 Comment(3)
Is it bad practice to use s(X,[]), np([a,woman],[]) and other queries of the same form ? If so why would these kinds of practices be used in learning materials ?Checky
Bad habits from the early days of Prolog, I assume.Basset
It's bad advice on the part of the Learning Prolog Now! website. They don't even mention phrase/2-3.Geostrophic
S
4

Actually, SWI-Prolog performs type checking (arguments must proper lists), then exhibits a performance penalty when using phrase/3.

Also, to allow for using a DCG and perform 'state threading', that is handing off to hidden parameters the state propagation, a call_dcg/3 has been introduced.

But for normal usage - lexical parsing and generation - phrase is the way to go.

Seibold answered 3/12, 2015 at 22:47 Comment(1)
Yes, but SWI-Prolog type checking in this case is quite light. In recent versions, it just checks that the second and third arguments are either variables or have a list functor.Basset
B
3

Grammar rules should always be accessed using the phrase/2-3 predicates. When the first argument is instantiated, the Prolog compiler should be expected to convert the phrase/2-3 call to a call to the predicate generated by the compilation of called grammar rule. Thus, there should be no overhead by using the phrase/2-3 predicates.

Basset answered 3/12, 2015 at 22:24 Comment(3)
Is it bad practice to use s(X,[]), np([a,woman],[]) and other queries of the same form ? If so why would these kinds of practices be used in learning materials ?Checky
Bad habits from the early days of Prolog, I assume.Basset
It's bad advice on the part of the Learning Prolog Now! website. They don't even mention phrase/2-3.Geostrophic

© 2022 - 2024 — McMap. All rights reserved.