Last active
June 30, 2024 14:46
-
-
Save trikitrok/fd5863c8624625b28e7f to your computer and use it in GitHub Desktop.
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
| ;; The first three lines of this file were inserted by DrRacket. They record metadata | |
| ;; about the language level of this file in a form that our tools can easily process. | |
| #reader(lib "htdp-advanced-reader.ss" "lang")((modname balance) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #t #t none #f ()))) | |
| (check-expect | |
| (balanced-parentheses? "") true) | |
| (check-expect | |
| (balanced-parentheses? "()") true) | |
| (check-expect | |
| (balanced-parentheses? "(moko)") true) | |
| (check-expect | |
| (balanced-parentheses? | |
| "(if (zero? x) max (/ 1 x))") | |
| true) | |
| (check-expect | |
| (balanced-parentheses? | |
| "I told him (that it’s not (yet) done). (But he wasn’t listening)") | |
| true) | |
| (check-expect | |
| (balanced-parentheses? ")") false) | |
| (check-expect | |
| (balanced-parentheses? "())( )") false) | |
| (check-expect | |
| (balanced-parentheses? "())(") false) | |
| (check-expect | |
| (balanced-parentheses? ":-)") false) | |
| (define (balanced-parentheses? str) | |
| (letrec | |
| ([f | |
| (lambda (char-list elements-in-stack) | |
| (cond ((empty? char-list) | |
| (= elements-in-stack 0)) | |
| ((char=? (car char-list) #\() | |
| (f (cdr char-list) (+ elements-in-stack 1))) | |
| ((and (char=? (car char-list) #\)) | |
| (= elements-in-stack 0)) | |
| false) | |
| ((char=? (car char-list) #\)) | |
| (f (cdr char-list) (- elements-in-stack 1))) | |
| (else | |
| (f (cdr char-list) elements-in-stack))))]) | |
| (f (string->list str) 0))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment