Reverse a string: Difference between revisions

Added implementation for 'fe' language
(Added implementation for 'fe' language)
Line 1,542:
RET
END DYNASM
</syntaxhighlight>
 
=={{header|Fe}}==
In this language, strings are very limited and are not designed to store large text data, so there are no built-in operations to work with strings. But with the C API you can make functions that convert a string to a list and vice versa.
<syntaxhighlight lang="c">
#define MAXSTRINGLEN ( 1024 )
 
/* chop string to list of single character strings */
static fe_Object* chop(fe_Context *ctx, fe_Object *args) {
char buf[MAXSTRINGLEN];
int len = fe_tostring(ctx, fe_nextarg(ctx, &args), buf, sizeof(buf));
int gc = fe_savegc(ctx);
args = fe_bool(ctx, 0);
while (len > 0) {
buf[len--] = '\0';
args = fe_cons(ctx, fe_string(ctx, buf + len), args);
fe_restoregc(ctx, gc);
fe_pushgc(ctx, args);
}
return args;
}
 
/* pack list of strings to single string */
static fe_Object* pack(fe_Context *ctx, fe_Object *args) {
char buf[MAXSTRINGLEN], *ptr = buf;
for (args = fe_nextarg(ctx, &args); !fe_isnil(ctx, args);) {
ptr += fe_tostring(ctx, fe_nextarg(ctx, &args), ptr, buf + sizeof(buf) - ptr);
}
return fe_string(ctx, buf);
}
</syntaxhighlight>
So, we can manipulate strings like lists:
<syntaxhighlight lang="clojure">
; reverse list
(= reverse (fn (lst)
(let res nil)
(while lst
(= res (cons (car lst) res))
(= lst (cdr lst)))
res))
 
; chop string to list, reverse list and pack it back to string
(print (pack (reverse (chop "Hello world!"))))
</syntaxhighlight>
Output:
<syntaxhighlight lang="clojure">
!dlrow olleH
</syntaxhighlight>
 
18

edits