What are the pros and cons of using manual list iteration vs recursion through fail

前端 未结 3 1844
灰色年华
灰色年华 2020-12-07 01:53

I come up against this all the time, and I\'m never sure which way to attack it. Below are two methods for processing some season facts.

What I\'m trying to work out

3条回答
  •  情歌与酒
    2020-12-07 02:16

    method one seems wasteful since the facts are available, why bother building a list of them (especially a large list). This must have memory implications too if the list is large enough ?

    Yes, method 1 takes Θ(n) memory. It's primary benefit is that it is declarative, i.e. it has a straightforward logical meaning.

    Method 2, the "failure-driven loop" as Prolog programmers call it, takes constant memory, is procedural and may be preferred when you're doing procedural (extra-logical) things anyway; i.e., in I/O code it's ok to use it.

    Note that SWI-Prolog has a third way of writing this loop:

    forall(season(S), showseason(S)).
    

    This only works if showseason succeeds for each binding of season(S).

提交回复
热议问题