/* Tokenize a string (Rosetta Code) in Picat. http://rosettacode.org/wiki/Tokenize_a_string """ Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. """ This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import util. main => go. % using built-in split/2 and join/2 go => S="Hello,How,Are,You,Today", T = S.split(","), println(t=T), T.join(".").println(), nl. % As a oneliner go2 => "Hello,How,Are,You,Today".split(",").join(".").println(), nl. % % Using imperative definitions split2/2 and join2/2. % go3 => S="Hello,How,Are,You,Today", T = S.split2(","), println(t=T), T.join2(".").println(), nl. % recursive versions split3/2 and join3/2 go4 => "Hello,How,Are,You,Today".split3(",").join3(".").println(), nl. % Another approach, though not according to the task: % Simply replace "," with ".". go5 => S="Hello,How,Are,You,Today", S.replace(',','.').println(), println([cond(C=',','.',C) : C in S]), nl. % % Split a string into string given some split chars % % List = split(String, SplitChars) % split2(S,Chars) = V => V = [], T = [], foreach(I in 1..S.length) if membchk(S[I], Chars) then V := V ++ [T], T := [] else T := T ++ [S[I]] end end, V := V ++ [T]. % % Join a list of strings with a join character. % % Res = join(String,JoinChar) % join2(S,JoinChar) = Res => Len = S.length, Res = "", foreach(I in 1..Len-1) Res := Res ++ S[I] ++ JoinChar end, Res := Res ++ S[Len]. % % recursive versions % split3(String,SplitChar) = Splitted => split3(String,SplitChar,"","",Splitted). split3("",_,Word,List0,List) => List = [Word.reverse()|List0].reverse(). split3([C|S],SplitChar,Word,List0,List), membchk(C,SplitChar) => split3(S,SplitChar,[],[Word.reverse()|List0],List). split3([C|S],SplitChar,Word,List0,List), not membchk(C,SplitChar) => split3(S,SplitChar,[C|Word], List0,List). join3(List,JoinChar) = Joined => join3(List,JoinChar,"",Joined). join3([],_JoinChar,Joined0,Joined) => Joined = Joined0. % fix for skipping the ending "." join3([H],JoinChar,Joined0,Joined) => join3([],JoinChar,Joined0++H,Joined). join3([H|T],JoinChar,Joined0,Joined) => join3(T,JoinChar,Joined0++H++JoinChar,Joined).