How to resolve the algorithm Reverse a string step by step in the Fe programming language

Published on 12 May 2024 09:40 PM
#Fe

How to resolve the algorithm Reverse a string step by step in the Fe programming language

Table of Contents

Problem Statement

Take a string and reverse it. For example, "asdf" becomes "fdsa".

Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Reverse a string step by step in the Fe programming language

Source code in the fe programming language

#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);
}


; 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!"))))


!dlrow olleH


  

You may also check:How to resolve the algorithm SHA-1 step by step in the Neko programming language
You may also check:How to resolve the algorithm Pangram checker step by step in the Objeck programming language
You may also check:How to resolve the algorithm Mayan numerals step by step in the J programming language
You may also check:How to resolve the algorithm Zero to the zero power step by step in the XLISP programming language
You may also check:How to resolve the algorithm ASCII art diagram converter step by step in the AArch64 Assembly programming language