Search code examples
stringprologdivide

Prolog - separate string from integer


I have a list similar to this ['hello world'-2, 'another string'-2,...] and I need to separate the string from the integer number in order to process both. Any ideas on how to do that? I've tried this:

1 ?- term_string('hello world'-2,String),split_string(String,'-',' ',List).

String = "'hello world'-2",
List = ["'hello world'", "2"].

But this gives me a string of a string, I want just the string.


Solution

  • I think conversion to a string representation of a term then splitting a string is the wrong approach. It's a bit brute force and indirect. You can split the terms directly:

    split_term(A-B, [A, B]).
    split_list(L, R) :- maplist(split_term, L, R).
    
    ?- split_list(['hello world'-2, 'another string'-2], R).
    R = [['hello world', 2], ['another string', 2]].