I am trying to implement some simple predicates, something like my_length or my_append.
It is considered easy for me if we knew beforehand that we wanted to find the length of a list, or we wanted to append two lists. (i.e. I know what is input, what is output).
In Prolog, it is possible to do thing in other ways. Like my_length(L, 3), or my_append(A,B,[1,2,3]).
Sometimes, my code works. Sometimes, it doesn't.
I find it quite difficult to make sure it works in all sort of different ways. Unless it is just a helper predicate for myself, you never really know what your users want to test it with. Sometimes the problem can even be ill defined, it is unclear what should my_length(L, 5)
outputs, for example.
Are there any best practices for that?
For practical programming, I found it much easier to just ignore these other ways and focus on only a particular way of calling. That's how I get things done, I am just worried about the possibility that someone else call it in a different way.
Is there a way for me to make that restriction at the language level? Or should I?
In particular, I am trying to write my_length
such that it works for
- Specifying list, calculating length, and
- Specifying length, give me back a list that has length unbounded slot.
my_length([], 0).
my_length([_|T], A) :- my_length(T, TA), A is TA + 1.
That works fine both ways, except it prompts for more answers when I ask the reverse question, and then we get a stack overflow. We also can't do arithmetic with the length argument since it could be unspecified.
This is just a specific case.