mirror of
https://github.com/carp-lang/Carp.git
synced 2024-10-11 12:37:32 +03:00
a3dd41cea7
Strings I: A few functions
86 lines
2.5 KiB
Plaintext
86 lines
2.5 KiB
Plaintext
(defmodule String
|
|
|
|
(register = (Fn [&String &String] Bool))
|
|
(register /= (Fn [&String &String] Bool))
|
|
(register append (Fn [String String] String)) ;; TODO: should take a &String as its second argument?
|
|
(register delete (Fn [String] ()))
|
|
(register copy (Fn [&String] String))
|
|
(register count (Fn [&String] Int))
|
|
(register duplicate (Fn [&String] String))
|
|
(register cstr (Fn [&String] (Ptr Char)))
|
|
(register str (Fn [&String] String))
|
|
(register char-at (Fn [&String Int] Char))
|
|
(register chars (Fn [&String] (Array Char)))
|
|
(register from-chars (Fn [(Array Char)] String))
|
|
(register tail (λ [(Ref String)] String))
|
|
|
|
(defn head [s]
|
|
(char-at s 0))
|
|
|
|
(defn repeat [n inpt]
|
|
(let [str ""]
|
|
(do
|
|
(for [i 0 n]
|
|
(set! &str &(append @str @inpt)))
|
|
@str)))
|
|
|
|
;; A temporary version of this function, until we have some nicer way to write it
|
|
(defn split-by [s separators]
|
|
(let [len (count &s)
|
|
result (the (Array String) [])
|
|
cs (chars &s)
|
|
word @""]
|
|
(do
|
|
(for [i 0 len]
|
|
(let [c (Array.nth &cs i)]
|
|
(do
|
|
(if (Int.< 0 (Array.element-count &(the (Array Char) @&separators) @c))
|
|
(if (= 0 (String.count &word))
|
|
() ;; no word
|
|
(do (set! &result (Array.push-back @&result @&word))
|
|
(set! &word @"")))
|
|
(set! &word (append @&word (from-chars [@c])))))))
|
|
;; Some sweet code duplication for the final word:
|
|
(if (= 0 (String.count &word))
|
|
()
|
|
(do (set! &result (Array.push-back @&result @&word))
|
|
(set! &word @"")))
|
|
result)))
|
|
|
|
(defn words [s]
|
|
(split-by s [\space \tab]))
|
|
|
|
(defn lines [s]
|
|
(split-by s [\newline]))
|
|
|
|
(defn pad-left [len pad s]
|
|
(let [x (Int.max 0 (- len (count s)))]
|
|
(append (from-chars (Array.replicate x &pad)) @s)))
|
|
|
|
(defn pad-right [len pad s]
|
|
(let [x (Int.max 0 (- len (count s)))]
|
|
(append @s (from-chars (Array.replicate x &pad)))))
|
|
|
|
(defn count-char [s c]
|
|
(let-do [n 0]
|
|
(for [i 0 (count s)]
|
|
(when (= c (char-at s i))
|
|
(set! &n (Int.inc n))))
|
|
n))
|
|
|
|
(defn reverse [s]
|
|
(from-chars (Array.reverse (chars s))))
|
|
|
|
(defn empty? [s]
|
|
(Int.= (count s) 0))
|
|
)
|
|
|
|
|
|
(defdynamic string-join- [strs]
|
|
(if (= (count strs) 0)
|
|
'(String.copy "")
|
|
(list 'String.append (car strs) (string-join- (cdr strs)))))
|
|
|
|
(defmacro string-join [:rest strs]
|
|
(string-join- strs))
|