string_extra.sml 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. structure StringExtra = struct
  2. val empty = "";
  3. fun split sep str =
  4. let
  5. val chars = String.explode str;
  6. val sep_chars = String.explode sep;
  7. val sep_len = length sep_chars;
  8. val prefix_pred = ListExtra.is_list_prefix sep_chars;
  9. fun iter (nil, collected_chars, parts) = String.implode (rev collected_chars) :: parts
  10. | iter (remaining_chars as (c::cs), collected_chars, parts) =
  11. if prefix_pred remaining_chars
  12. then
  13. (* drop the separator, begin anew collecting chars until next separator, *)
  14. iter (List.drop (remaining_chars, sep_len),
  15. [],
  16. String.implode (rev collected_chars) :: parts)
  17. else
  18. (* collect characters, which are not part of the prefix *)
  19. iter (cs, c :: collected_chars, parts)
  20. in
  21. rev (iter (chars, [], []))
  22. end;
  23. fun replace searched replacement str =
  24. let
  25. val len_searched = String.size searched;
  26. val chars = String.explode str;
  27. val searched_chars = String.explode searched;
  28. val replacement_chars = String.explode replacement;
  29. val starts_with_searched = ListExtra.is_list_prefix searched_chars;
  30. fun iter nil = []
  31. | iter remaining_chars =
  32. if starts_with_searched remaining_chars
  33. then
  34. ListExtra.prepend replacement_chars
  35. (iter (List.drop (remaining_chars, len_searched)))
  36. else
  37. (hd remaining_chars) :: iter (tl remaining_chars);
  38. in
  39. String.implode (iter chars)
  40. end;
  41. fun trim_left pred str =
  42. let
  43. fun iter nil = []
  44. | iter (chars as (c::cs)) =
  45. if pred c
  46. then iter cs
  47. else chars
  48. in
  49. String.implode (iter (String.explode str))
  50. end;
  51. end;