Can you do Logic Programming in Scala?

Alex R picture Alex R · Apr 17, 2010 · Viewed 7.1k times · Source

I read somewhere that Pattern Matching like that supported by the match/case feature in Scala was actually borrowed from Logic languages like Prolog.

Can you use Scala to elegantly solve problems like the Connected Graph problem? e.g. https://www.csupomona.edu/~jrfisher/www/prolog_tutorial/2_15.html

Answer

Daniel C. Sobral picture Daniel C. Sobral · Apr 17, 2010

No, you can't do it, unless you actually create a logic engine, which kind of defeats the whole purpose.

Furthermore, pattern matching itself is wholly unsuited for this, for many reasons. Consider, for instance, the basic query itself: path(1, 5, P). In Scala's pattern matching, 1, 5 and P are outputs. You can't provide an input that could be used to produce the output.

With Prolog, this is like, assuming that 1 and 5 are fixed, what possible values could P take on? That's just now how pattern matching works.

Edit: With Scala 2.10, pattern matching is now compiled to an intermediate operation like for-comprehensions are, and then the default translation is further optimized. However, it is possible to define your own class to handle pattern matching, and I have seen it used to implement prolog login -- though I can't find the link, sorry.