Skip to content

Instantly share code, notes, and snippets.

@cristeigabriel
Last active July 11, 2022 11:11
Show Gist options
  • Save cristeigabriel/362ce0cfe43893818a8d96b92a78d7a7 to your computer and use it in GitHub Desktop.
Save cristeigabriel/362ce0cfe43893818a8d96b92a78d7a7 to your computer and use it in GitHub Desktop.
Scheme Lisp compatible atoi imlpementation. Handles negation and trailing zeros.
#lang sicp
;; power impl
;; x - number
;; y - power
;; z - preserved base
(define (^-impl x y z) (if (<= y 0)
x
(^-impl (* z x) (- y 1) z)))
;; power
;; x - number
;; y - power
;; returns:
;; x <= 0 => 1
;; x > 0 => (x^y)
(define (^ x y) (if (<= y 0)
1
(^-impl x (- y 1) x)))
;; atoi
;; x - carry string as list (expected numeric)
;; y - carry integer
;; z - carry power
(define (atoi-impl x y z) (if (<= (length x) 0)
y
(atoi-impl (cdr x) (+ y (* (string->number (string (car x))) (^ 10 z))) (- z 1))))
;; skip heading char
;; x - string to list
;; y - string to skip
(define (skip-heading-char x y)
(if (equal? (string (car x)) y)
(skip-heading-char (cdr x) y)
x))
;; atoi
;; x - string
(define (atoi x)
(let ((negative? (equal? (string (car (string->list x))) "-")))
(let ((x-list (skip-heading-char (if negative? (cdr (string->list x)) (string->list x)) "0")))
(* (atoi-impl x-list 0 (- (length x-list) 1)) (if negative? -1 1)))))
(display (atoi "00133742069"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment