OK, I have a string like this
this/is/the/type/char*
and I want a predicate that can remove the char* from the end returning it as the type, and then return everything before “/char*” as the resultant variable name as that’s how it works. In any imperative language I care to mention this would be an absolute doddle but for some reason the likes of sub_string and split_string are driving me nuts. The problem is if you give it a string with a trailing slash.
I know I am using split_string with the same pad and sep chars to remove duplicated occurrences. I am wondering if the predicate below is even on the right track.
var_type(Var, VarOut,Type) :-
split_string(Var, "/", "/", Parts),
length(Parts, L),
L > 1,
!,
last(Parts, Type),
string_length(Var, VLen), % Now we just drop the prefix
string_length(Type, TLen), % from the end of the source
PLen is VLen - TLen -1 , % including the trailing "/"
print([VLen, TLen, PLen]),
sub_string(Var, 0, PLen, _, VarOut)
ast: ?- var_type("score/longint/the/last/char*/", Var, Type).
[29,5,23]
Var = "score/longint/the/last/",
Type = "char*".
ast: ?- var_type("score/longint/the/last/char*", Var, Type).
[28,5,22]
Var = "score/longint/the/last",
Type = "char*".
ast: ?- var_type("score/longint", Var, Type).
[13,7,5]
Var = "score",
Type = "longint".
ast: ?- var_type("score/", Var, Type).
false.
ast: ?- var_type("score", Var, Type).
false.
The last two fail but that’s fine as it indicates no trailing type was given in the string. Essentially if the string ends with “/” I should probably reject it in the first place, so I will follow that but I can’t believe how ugly it all feels at this point.
Any guidance / notes on more idiomatic style would be very much appreciated at this juncture!
Thanks.,
Sean.