0

I'm really new to prolog and i have to write a predicate what takes in a string and an integer and writes out as many characters of that string as the integer value is. How can i do this ? Example:

myPredicate('Hello',4). %will write out 'Hell'
myPredicate('New in prolog',6). %will write out 'New in' 
Marek
  • 261
  • 4
  • 14

1 Answers1

1

format it's the appropriate predicate to perform formatted output, but it doesn't provide a truncation of values. Then you could define a service predicate like print_n/2:

6 ?- [user].
|: print_n(W,N) :- sub_atom(W,0,N,_,S),write(S).
% user://1 compiled 0.04 sec, 2 clauses
true.

7 ?- print_n(hello,3).
hel
true.

then format/2 can invoke your service predicate by means of @:

8 ?- format('hello ~@~n', [print_n(world,3)]).
hello wor
true.
CapelliC
  • 59,646
  • 5
  • 47
  • 90