How to join two utf8 strings together in Clarity? - blockchain

In my Clarity smart contract, I am trying to to append one string ("Hello") to another string (" to Clarity Language"). Both strings are of type string-utf8.
Deploying the contract below fails with an error: expecting expression of type \'(string-utf8 100)\', found \'(string-utf8 120)\'
(define-data-var a-string (string-utf8 100) u"Hello")
(var-set a-string (concat (var-get a-string) u" to Clarity Language"))
(print (var-get a-string))
How to make this work?

concat does not optimize the resulting string. The new string is of type string-utf8 with length 120, adding the length of the variable type to the length of the other string (100 + 20).
You have to wrap the concat call with a as-max-len?:
(define-data-var a-string (string-utf8 100) u"Hello")
(var-set a-string
(unwrap! (as-max-len?
(concat (var-get a-string) u" to Clarity Language") u100) (err "text too long")))
(print (var-get a-string))
Note, that the type length is defined by an int (100), while as-max-len? takes a uint parameter (u100).

Related

Clojure int to char (e.g. 1 to \1)

Is their a way in Clojure to go from an int to that int as a character, e.g. 1 to \1 ?
I have a string s and I want to parse out the digits that match a number n (n will always be 0 to 9)
e.g.
(let [n 1]
(filter #(= ??? %) "123123123"))
Where ??? would n as \n, e.g. would return "111"
Or maybe there is a better way to filter a string to only instance of a single digit?
The "java" way:
user=> (Character/forDigit 1 10) ; number and radix
\1
The "calculaty" way (add the int of \0 to it and then back to char):
user=> (char (+ 1 (int \0)))
\1
And as usual in Clojure, there's always a reduce one-line to solve the original problem: "I just want the count of how many times that digit appears."
(reduce (fn [m ch] (update m ch (fnil inc 0))) {} "123123123")
==> {\1 3, \2 3, \3 3}
A lot to unpack here, if you are new to Clojure.
Reduce is used to iterate over the String, counting occurrences of each character and storing it in a map.
From inner to outer:
(fnil inc 0) returns a function that runs inc with any argument provided. However, if the argument is nil, it will replace it with 0 instead. This is perfect for adding a new entry to the map.
update is used to look up an existing key ch in m and calculate a new value (by calling the function returned by (fnil inc 0)), i.e. if the ch is not in m this will run (inc 0) => 1, if ch is in m it will return the incremented counter.
(fn [m ch] ...) is the reducing function.
This is the most difficult part to understand. It takes two parameters.
The first is the last return value of this function (generated by an earlier iteration) or if it is the first time this function runs, the initial value provided: {} (there's also a third way to call reduce, see (doc reduce))
The second argument ch is the current character in the String provided (since String is a CharSequence and counts as a collection).
So the reducing function is called for each character and we just return the current map with an updated count for each character, starting with {}.

How can I convert char to symbol in common lisp?

Total lisp beginner here.
I'm wondering how to convert a character to symbol. Simply what I want is convert #\a to a
Here what I have done so far:
(defun convert(char)
(if(eq char #\a)
(setq char 'a))
char)
This one is works actually but I don't want to add 26 conditions(letters in alphabet) and make a long-dumb code.
Also I'm wondering is there any functions in common lisp that converts character list to symbol list like: (#\h #\e #\l #\l #\o) to (h e l l o) ? I have found intern and make-symbol related to that but they require string as parameter.
CL-USER 230 > (intern (string #\Q))
Q
NIL
CL-USER 231 > (intern (string #\q))
\q
NIL
Btw., your code has a bunch of improvements necessary:
(defun convert(char) ;
(if(eq char #\a) ; use EQL instead of EQ for characters
; indentation is wrong
(setq char 'a)) ; indentation is wrong
char) ; indentation is wrong
Better write it as:
(defun convert (char)
(if (eql char #\a)
'a
char))
or
(defun convert (char)
(case char
(#\a 'a)
(#\b 'b)
(otherwise char)))
As mentioned above, the 'real' solution is:
(defun convert (char)
(intern (string char)))
(defun converter (c)
(if (characterp c)
(make-symbol (string c))))
You could use make-symbol and convert the symbol to a string.
(setq my-sym (converter #\a))
Answering my own question after a while:
Also I'm wondering is there any functions in common lisp that converts character list to symbol list like: (#\h #\e #\l #\l #\o) to (h e l l o) ?
I can convert single character to symbol with this convert function:
(defun convert (c)
(if (characterp c)
(intern (string c))))
Since one of main ideas of LISP is "processing a list" I can use one of map functions to apply one operation to every single element of the list.
(mapcar #'convert '(#\h #\e #\l #\l #\o))
Here mapcar function will result the list of symbols:
(|h| |e| |l| |l| |o|)

Check string length with variable in Clojure

I want a function written in Clojure that checks if my given String is bigger than my given number and if so, my function says true otherwise it says false.
Now i've come up with the following code, but it gives the following error:
ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn user/checker (form-init1692807253513002836.clj:1)
The code i've come up with is:
(defn checker [str, num]
(cond
(> (count str) num) "True"
:else "False"
)
)
(checker "test" 6)
Can someone explain why count str is considered as a Long and/or how this function can be fixed?
You might want to “fix” your function by considering some Clojure
idioms that apply to your snippet:
booleans are built in; no need to use "True"/"False" strings
(unless you’re just using these as a placeholder example for
something else)
don’t need to be explicit about the return booleans since >
already returns a boolean
you’re measuring “length” rather than “bigness”, so use a
descriptive function name; strlen is probably common
since boolean return value you can end with ?
probably avoid str as var name
switch the comparison order to use < instead of >, based on Elements of Clojure recommendation
With those in mind, your function simplifies down to:
(defn strlen-exceeds? [s n]
(< n (count s)))
(And now it’s short enough that you might not even need it to be an
explicit function.)
I think your code should work, but for this case, don't use cond use if.
(defn checker [str, num]
(if (> (count str) num)
"True"
"False"))
> (checker "a" 1)
"False"
> (checker "a" 2)
"False"
> (checker "ab" 2)
"False"
> (checker "ab" 2)

Looking for a replace-in-string function in elisp

I'm looking for an equivalent of replace-regexp-in-string that just uses literal strings, no regular expressions.
(replace-regexp-in-string "." "bar" "foo.buzz") => "barbarbarbarbarbarbarbar"
But I want
(replace-in-string "." "bar" "foo.buzz") => "foobarbuzz"
I tried various replace-* functions but can't figure it out.
Edit
In return for the elaborate answers I decided to benchmark them (yea, I know all benchmarks are wrong, but it's still interesting).
The output of benchmark-run is (time, # garbage collections, GC time):
(benchmark-run 10000
(replace-regexp-in-string "." "bar" "foo.buzz"))
=> (0.5530160000000001 7 0.4121459999999999)
(benchmark-run 10000
(haxe-replace-string "." "bar" "foo.buzz"))
=> (5.301392 68 3.851943000000009)
(benchmark-run 10000
(replace-string-in-string "." "bar" "foo.buzz"))
=> (1.429293 5 0.29774799999999857)
replace-regexp-in-string with a quoted regexp wins. Temporary buffers do remarkably well.
Edit 2
Now with compilation! Had to do 10x more iteration:
(benchmark-run 100000
(haxe-replace-string "." "bar" "foo.buzz"))
=> (0.8736970000000001 14 0.47306700000000035)
(benchmark-run 100000
(replace-in-string "." "bar" "foo.buzz"))
=> (1.25983 29 0.9721819999999983)
(benchmark-run 100000
(replace-string-in-string "." "bar" "foo.buzz"))
=> (11.877136 86 3.1208540000000013)
haxe-replace-string is looking good
Try this:
(defun replace-in-string (what with in)
(replace-regexp-in-string (regexp-quote what) with in nil 'literal))
s.el string manipulation library has s-replace function:
(s-replace "." "bar" "foo.buzz") ;; => "foobarbuzz"
I recommend installing s.el from Emacs package manager, if you work with strings in your Elisp.
Emacs 28.1 (still in development at time of writing) provides this as standard:
** New function 'string-replace'.
This function works along the line of 'replace-regexp-in-string', but
matching on strings instead of regexps, and does not change the global
match state.
(string-replace FROMSTRING TOSTRING INSTRING)
Replace FROMSTRING with TOSTRING in INSTRING each time it occurs.
(string-replace ".*" "BAR" "foo.*bar.*baz")
⇒ "fooBARbarBARbaz"
I'd not hope for this to be faster:
(defun haxe-replace-string (string string-a string-b)
"Because there's no function in eLisp to do this."
(loop for i from 0 upto
(- (length string) (length string-a))
for c = (aref string i)
with alen = (length string-a)
with result = nil
with last = 0
do (loop for j from i below (+ i alen)
do (unless
(char-equal
(aref string-a (- j i))
(aref string j))
(return))
finally
(setq result
(cons (substring string last (- j alen)) result)
i (1- j) last j))
finally
(return
(if result
(mapconcat
#'identity
(reverse (cons (substring string last) result)) string-b)
string))))
Becasue replace-regexp-in-string is a native function, but you never know... Anyways, I wrote this some time ago for some reason, so, if you fill like comparing the performance - you are welcome to try :)
Another idea, using temporary buffer:
(defun replace-string-in-string (what with in)
(with-temp-buffer
(insert in)
(beginning-of-buffer)
(while (search-forward what nil t)
(replace-match with nil t))
(buffer-string)))
s-replace is fine if you are ready to require it, but say you want to use a replace in string feature early in the load process and don't yet have s.el loaded or don't need all of it. Well, here is the definition of s-replace from s.el. As you can see, it has no dependencies so you can use it without requiring the rest of s.el:
(defun s-replace (old new s)
"Replaces OLD with NEW in S."
(declare (pure t) (side-effect-free t))
(replace-regexp-in-string (regexp-quote old) new s t t))

LISP: Force evaluation

I'm taking a list name as input with a single quote ('), but after doing a few operations, I want to actually evaluate it instead of treat it as an atom.
So for example, just for simplicity sake, I have the following list:
(setf LT '(A B C))
I have a function called SEP. To run the function, I must run it as (SEP 'LT). So as you can see, LISP will interpret LT as an atom instead of evaluate it as a list, which is not what I want.
So essentially, I want (SEP 'LT) to really become (SEP '(A B C)) somehow.
The input format can't be changed. Any help would be appreciated. Thanks!
If LT is a top-level variable, defined with defvar, then you can get its value with symbol-value as such:
* (symbol-value 'lt)
(A B C)
* (defun sep (name)
(assert (symbolp name))
(let ((value (symbol-value name)))
...