Created
August 11, 2021 04:13
-
-
Save yanfeng42/f5f32c01108460f2433f71097ace1da8 to your computer and use it in GitHub Desktop.
2.2 的 swift 版实现 -- 先用swift 模拟 cons car cdr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// mirror... | |
func cons<T0, T1>(_ x: T0, _ y: T1) -> (T0, T1) { | |
return (x, y) | |
} | |
func car<T0, T1>(_ t:(T0, T1)) -> T0 { | |
return t.0 | |
} | |
func cdr<T0, T1>(_ t:(T0, T1)) -> T1 { | |
return t.1 | |
} | |
// sample... | |
//(define (make-segment start end) (cons start end)) | |
func makeSegment<T0, T1>(_ start:T0, _ end: T1) -> (T0, T1) { cons(start, end) } | |
//(define (start-segment s) (car s)) | |
func startSegment<T0, T1>(_ s: (T0, T1)) -> T0 { car(s) } | |
//(define (end-segment s) (cdr s)) | |
func endSegment<T0, T1>(_ s: (T0, T1)) -> T1 { cdr(s) } | |
// | |
//(define (make-point x y) (cons x y)) | |
func makePoint<T0, T1>(_ x:T0, _ y: T1) -> (T0, T1) { cons(x, y) } | |
//(define (x-point p) (car p)) | |
func xPoint<T0, T1>(_ p: (T0, T1)) -> T0 { car(p) } | |
//(define (y-point p) (cdr p)) | |
func yPoint<T0, T1>(_ p: (T0, T1)) -> T1 { cdr(p) } | |
// | |
//(define (midpoint-segment s) | |
// (let ((x (/ (+ (x-point (end-segment s)) (x-point (start-segment s))) 2)) | |
// (y (/ (+ (y-point (end-segment s)) (y-point (start-segment s))) 2)) ) | |
// (make-point x y) | |
// ) | |
//) | |
func midpointSegment(_ s: ((Double, Double), (Double, Double))) -> (Double, Double){ | |
let x = ((xPoint(endSegment(s))) + (xPoint(startSegment(s)))) / 2.0 | |
let y = ((yPoint(endSegment(s))) + (yPoint(startSegment(s)))) / 2.0 | |
return cons(x, y) | |
} | |
//(define (print-point p) | |
// (newline) | |
// (display "(") | |
// (display (x-point p)) | |
// (display ",") | |
// (display (y-point p)) | |
// (display ")") | |
//) | |
func printPoint<T0, T1>(_ p: (T0, T1)) { | |
print("\n(\(xPoint(p)), \(yPoint(p)))") | |
} | |
//; test case (15,15) | |
//(print-point (midpoint-segment (make-segment (make-point 10 10) (make-point 20 20)))) | |
(printPoint((midpointSegment((makeSegment((makePoint(10.0, 10.0)), (makePoint(20.0, 20.0)))))))) // output: (15.0, 15.0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment