浏览代码

Add str_replace and tests

David Peter 2 年之前
父节点
当前提交
92e4188dfd
共有 3 个文件被更改,包括 39 次插入0 次删除
  1. 9 0
      book/src/list-functions.md
  2. 21 0
      examples/prelude_tests.nbt
  3. 9 0
      numbat/modules/core/strings.nbt

+ 9 - 0
book/src/list-functions.md

@@ -85,3 +85,12 @@ you also get access to:
 * `fn to_celsius(t_kelvin: Temperature) -> Scalar`
 * `fn to_celsius(t_kelvin: Temperature) -> Scalar`
 * `fn from_fahrenheit(t_fahrenheit: Scalar) -> Temperature`
 * `fn from_fahrenheit(t_fahrenheit: Scalar) -> Temperature`
 * `fn to_fahrenheit(t_kelvin: Temperature) -> Scalar`
 * `fn to_fahrenheit(t_kelvin: Temperature) -> Scalar`
+
+## Strings
+
+* `fn str_length(s: str) -> Scalar`
+* `fn str_slice(s: str, start: Scalar, end: Scalar) -> str`
+* `fn str_append(a: str, b: str) -> str`
+* `fn str_contains(haystack: str, needle: str) -> bool`
+* `fn str_replace(s: str, pattern: str, replacement: str) -> str`
+* `fn str_repeat(a: str, n: Scalar) -> str`

+ 21 - 0
examples/prelude_tests.nbt

@@ -51,3 +51,24 @@ assert_eq(asech(0.3), 1.873820, 1e-5)
 
 
 assert_eq(csch(0.3), 3.283853, 1e-5)
 assert_eq(csch(0.3), 3.283853, 1e-5)
 assert_eq(acsch(0.3), 1.918896, 1e-5)
 assert_eq(acsch(0.3), 1.918896, 1e-5)
+
+# strings
+
+assert_eq(str_length(""), 0)
+assert_eq(str_length("foo"), 3)
+
+assert(str_slice("hello world", 0, 5) == "hello")
+assert(str_slice("hello world", 6, 11) == "world")
+assert(str_slice("hello world", 0, 0) == "")
+assert(str_slice("hello world", 0, 100) == "")
+
+assert(str_append("foo", "bar") == "foobar")
+
+assert(str_contains("hello world", "hello"))
+assert(str_contains("hello world", "world"))
+assert(str_contains("hello world", "HELLO") == false)
+
+assert(str_replace("hello world", "hello", "HEY") == "HEY world")
+assert(str_replace("xxx", "x", "yY") == "yYyYyY")
+
+assert(str_repeat("xy", 3) == "xyxyxy")

+ 9 - 0
numbat/modules/core/strings.nbt

@@ -13,6 +13,15 @@ fn str_contains(haystack: str, needle: str) -> bool =
       then true
       then true
       else str_contains(str_slice(haystack, 1, str_length(haystack)), needle)
       else str_contains(str_slice(haystack, 1, str_length(haystack)), needle)
 
 
+fn str_replace(s: str, pattern: str, replacement: str) -> str =
+  if pattern == ""
+    then s
+    else if str_contains(s, pattern)
+           then if str_slice(s, 0, str_length(pattern)) == pattern
+               then str_replace(str_append(replacement, str_slice(s, str_length(pattern), str_length(s))), pattern, replacement)
+               else str_append(str_slice(s, 0, 1), str_replace(str_slice(s, 1, str_length(s)), pattern, replacement))
+           else s
+
 fn str_repeat(a: str, n: Scalar) -> str =
 fn str_repeat(a: str, n: Scalar) -> str =
   if n > 0
   if n > 0
     then str_append(a, str_repeat(a, n - 1))
     then str_append(a, str_repeat(a, n - 1))