/* Binary strings (Rosetta code) in Picat. http://rosettacode.org/wiki/Binary_strings """ Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them. If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language. In particular the functions you need to create are: - String creation and destruction (when needed and if there's no garbage collection or similar mechanism) - String assignment - String comparison - String cloning and copying - Check if a string is empty - Append a byte to a string - Extract a substring from a string - Replace every occurrence of a byte (or a string) in a string with another string - Join strings Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more. """ This program was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import util. main => go. go => % - String creation and destruction (when needed and if there's no garbage % collection or similar mechanism) % - String assignment S1 = "binary_string", println(s1=S1), % Picat has re-assignments (:=/2) as well, S1 := "another string", println(s1=S1), % - String comparison if S1 == "another string" then println(same) else println(not_same) end, % - String cloning and copying S2 = S1, println(s2=S2), S3 = copy_term(S1), % for strings it's the same as =/2 println(s3=S3), % - Check if a string is empty if S3 == "" then println(is_empty) else println(not_empty) end, % - Append a byte to a string S3 := S3 ++ "s", println(s3=S3), % - Extract a substring from a string println(substring=S3[5..7]), println(slice=slice(S1,5,7)), println(slice=slice(S1,5)), % - Replace every occurrence of a byte (or a string) in a string with another string S4 = replace(S3,'s','x'), println(s4=S4), % - Join strings S5 = S1 ++ " " ++ S2, println(s5=S5), % using append/4 append(S1," ", S2,S6), println(s6=S6), % find positions of substrings println(find=findall([From,To],find(S5,"str",From,To))), % split a string println(split=split(S1," st")), nl, % A string is a list of characters so all list functions/procedures are supported println(member=findall(C,(member(C,S1), C @< 'l') )), % find substrings using append/3 S = "string", println(append=findall([A,B],append(A,B,S))), println(append=findall([A,B],append(A,"r",B,S))), println(select=findall([C,NewS],select(C,S,NewS))), % list comprehension println(list_comprehension=[ C : C in S5, membchk(C,"aeiou")]), println(sort_remove_dups=sort_remove_dups(S5)), nl.