Skip to content

Instantly share code, notes, and snippets.

@VitalyAnkh
Created May 18, 2022 17:08
Show Gist options
  • Save VitalyAnkh/02292193112bacd87f4e1be5abda4134 to your computer and use it in GitHub Desktop.
Save VitalyAnkh/02292193112bacd87f4e1be5abda4134 to your computer and use it in GitHub Desktop.
sicp_polyglot.org

sicp-polyglot

Chapter 1. Building Abstraction with Procedures

Square Roots by Newton’s Method

Rust

fn average(x: f64, y: f64) -> f64 {
    (x + y) / 2.0
}
fn abs(a: f64) -> f64 {
    if a <= 0f64 {
        -a
    } else {
        a
    }
}
fn good_enough(guess: f64, x: f64) -> bool {
    if abs(guess - x) <= 0.01 {
        true
    } else {
        false
    }
}
fn improve(guess: f64, x: f64) -> f64 {
    (x / guess + guess) / 2.0
}
fn sqrt_iter(guess: f64, x: f64) -> f64 {
    if good_enough(guess, x) {
        guess
    } else {
        sqrt_iter(improve(guess, x), x)
    }
}
fn sqrt(x: f64) -> f64 {
    sqrt_iter(1.0, x)
}
fn main() {
    sqrt(3.0);
}

Scala

def loop: Boolean = loop

Python

print("hello")

Exercise 1.6: if as an ordinary procedure

Rust

Scala

Python

EmacsLisp

Common Lisp

Racket

#lang racket
(define (new-if predicate then-clause else-clause)
(cond (predicate then-clause)
      (else else-clause)))

(define (use-new-if x) (new-if (= x 0) 1 (/ 1 x)))
(use-new-if 0)

OCaml

Exercise 1.7: improve good-enough?

Racket

#lang racket
(define (average x y) (/ (+ x y) 2))
(define (improve guess x)
  (average guess (/ x guess))
  )
(define (good-enough? guess x)
  (< (/ (abs (- (improve guess x) guess)) guess) 0.00001))

(define (sqrt-iter guess x)
  (if (good-enough? guess x)
      guess
      (sqrt-iter (improve guess x) x))
  )

(define (sqrt x)
  (sqrt-iter 1.0 x)
  )
(sqrt 300000000)
(sqrt 0.000000001)
(sqrt 10000000000000000003214.0)

Fibonacci numbers using tree recursion

#lang racket
(define (fib n)
  (cond
    ((= n 0) 0)
    ((= n 1) 1)
    (else (+ (fib (- n 1)) (fib (- n 2))))))
(fib 10)

Fibnocci using iteration

#lang racket
(define (fib-iter a b n)
  (cond
    ((= n 0) a)
    ((= n 1) b)
    (else (fib-iter b (+ a b) (- n 1)))))
(define (fib n)
  (fib-iter 0 1 n))
(fib 10)

Exercise 1.15: The sine of an angle

Racket
#lang racket
(define (cube x) (* x x x))
(define (p x) (- (* 3 x) (* 4 (cube x))))
(define (sine angle)
  (if (not (> (abs angle) 0.1))
      angle
      (p (sine (/ angle 3.0))))
  )
(sine 5.68)
Haskell
cube :: Int -> Int
cube x = x *x *x

Chapter 2. Building Abstractions with Data

Chapter 3. Modularity, Objects and State

Chapter 4. Metalinguistic Abstraction

Chapter 5. Computing with Register Machines

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment