Prolog: slash separated string to list

Viewed 68

I have a string like '/home/user/something/' and I want to convert it to ['/', 'home', '/', 'user', '/', 'something', '/']

How can I do this?

1 Answers

1- s predicate takes the input and gives the final split answer.

2- split_string is used to return just the words, so it returns L = ["home", "user", "something"]. Notice we don't have the /.

3- Now we need to add the "/". We use addslash predicate, before every word we add a "/". For the last "/" it checks the base predicate and the last "/" is added to the list.

s(X,L1):-
    split_string(X, "/", "/", L),
    addslash(L,L1).

addslash([],["/"]).
addslash([H|T],[H1,H|L]):-
    H1="/",
    addslash(T,L).


?- s('/home/user/something/', L).
L = ["/", "home", "/", "user", "/", "something", "/"]
Related