Δευτέρα 16 Μαρτίου 2020

Base Conversion an Example

First publish here in Rosettacode.org

The code is very compact. We use here ** for power (also ^ can be used for power).
M2000 is like Basic, but with advance constructions like lambda functions. Each lambda function return not a lambda but the result of a new lambda (see the immediate call using (m) and (m$) after the block {} in each lambda. The closures z$ and b are there for each recursive call.


Module Checkit {
 k$=lambda$ (m, b as integer=16) -> {
  if b<2 or b>16 then error "base out of range"
  if m=0 then ="0" : exit
  z$="0123456789ABCDEF" 
  =lambda$ z$, b (m) ->{
   =if$(m=0->"", lambda$(m div b)+mid$(z$, m mod b + 1, 1))
  }(m)
 }
 k=lambda (m$, b as integer=16) -> {
  if b<2 or b>16 then error "base out of range"
  m$=trim$(m$)
  if m$="0" then =0 : exit
  z$="0123456789ABCDEF" 
  =lambda z$, b (m$) ->{
   =if(Len(m$)=0->0, lambda(mid$(m$,2))+(instr(z$, left$(m$,1))-1)*b**(len(m$)-1))
  }(m$)
 }
 Print k$(0)="0", k("0")=0
 Print k$(65535)="FFFF", k("FFFF", 16)=65535
 Print k$(0xF00F)="F00F", k("F00F", 16)=0xF00F
 Print k$(0xFFFFFFFF)="FFFFFFFF", k("FFFFFFFF", 16)=0xFFFFFFFF
 Print k$(100, 8)="144", k("144", 8)=100
 Print k$(100, 2)="1100100", k("1100100", 2)=100
}
Checkit

Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου

You can feel free to write any suggestion, or idea on the subject.