TIL: How to Design Programs, Raft Consensus Algorithm, DWIM Philosophy, and The Jargon File
Today I learned about the systematic program design methodology from HtDP, the elegant Raft consensus algorithm visualization, the DWIM (Do What I Mean) principle in computing, and the legendary Jargon File documenting hacker culture.
;; Data Definition;; A List-of-Numbers is one of:;; - empty;; - (cons Number List-of-Numbers);; Contract and Purpose;; sum : List-of-Numbers -> Number ;; Computes the sum of all numbers in the list;; Examples;; (sum empty) should produce 0;; (sum (cons 3 (cons 7 empty))) should produce 10;; Template (follows the data structure)(define (sumlon)(cond[(empty?lon)...][(cons?lon)(...(firstlon)...(sum(restlon))...)]));; Body (fill in the template)(define (sumlon)(cond[(empty?lon)0][(cons?lon)(+ (firstlon)(sum(restlon)))]));; Testing(check-expect(sumempty)0)(check-expect(sum(cons 3(cons 7empty)))10)
;; Binary Tree data definition;; A BT is one of:;; - 'leaf;; - (make-node Number BT BT)(define-structnode(valueleftright));; Template automatically follows data structure(define (bt-templatebt)(cond[(symbol? bt)...]; leaf case[(node?bt)(...(node-valuebt); node case(bt-template(node-leftbt))(bt-template(node-rightbt)))]));; Count nodes in binary tree(define (count-nodesbt)(cond[(symbol? bt)0][(node?bt)(+ 1(count-nodes(node-leftbt))(count-nodes(node-rightbt)))]))
# HtDP principles in PythonfromtypingimportList,Unionfromdataclassesimportdataclass# Data Definition@dataclassclassEmpty:pass@dataclassclassNode:value:intrest:Union['Node',Empty]ListOfInts=Union[Node,Empty]# Contract and Purposedefsum_list(lst:ListOfInts)->int:"""Computes the sum of all integers in the list."""# Examples (as doctests)"""
>>> sum_list(Empty())
0
>>> sum_list(Node(3, Node(7, Empty())))
10
"""# Template follows data structureifisinstance(lst,Empty):return0elifisinstance(lst,Node):returnlst.value+sum_list(lst.rest)
# Pseudo-code for election logicclassRaftServer:def__init__(self):self.state="follower"self.current_term=0self.voted_for=Noneself.log=[]self.election_timeout=random_timeout()defstart_election(self):self.state="candidate"self.current_term+=1self.voted_for=self.server_idvotes_received=1# Vote for selfforserverinother_servers:vote_granted=server.request_vote(term=self.current_term,candidate_id=self.server_id,last_log_index=len(self.log)-1,last_log_term=self.log[-1].termifself.logelse0)ifvote_granted:votes_received+=1ifvotes_received>len(all_servers)//2:self.become_leader()else:self.become_follower()defrequest_vote(self,term,candidate_id,last_log_index,last_log_term):# Only vote if:# 1. Haven't voted in this term, or voted for this candidate# 2. Candidate's log is at least as up-to-date as oursif(term>self.current_termand(self.voted_forisNoneorself.voted_for==candidate_id)andself.log_is_up_to_date(last_log_index,last_log_term)):self.voted_for=candidate_idself.current_term=termreturnTruereturnFalse
classLogEntry:def__init__(self,term,command):self.term=termself.command=commandclassRaftLeader:defreplicate_entry(self,command):# Append to local logentry=LogEntry(self.current_term,command)self.log.append(entry)# Send to followersresponses=[]forfollowerinself.followers:response=follower.append_entries(term=self.current_term,leader_id=self.server_id,prev_log_index=len(self.log)-2,prev_log_term=self.log[-2].termiflen(self.log)>1else0,entries=[entry],leader_commit=self.commit_index)responses.append(response)# Check for majoritysuccess_count=sum(1forrinresponsesifr.success)+1# +1 for leaderifsuccess_count>len(self.all_servers)//2:self.commit_index=len(self.log)-1returnTruereturnFalse
;; Original DWIM in LISP;; If user types (CAR X Y) instead of (CAR (X Y));; System might auto-correct to intended meaning;; But ambiguity arises:(SETQFOO(CARXY)); What did user mean?;; Option 1: (SETQ FOO (CAR (X Y)));; Option 2: (SETQ FOO (CAR X) Y) ;; Option 3: Syntax error
# Python's flexible type systemdefadd_items(items):# Works with lists, tuples, strings, etc.result=[]foriteminitems:# DWIM: iterate over any iterableresult.append(item)returnresult# Shell command completion$gitco<TAB># Expands to 'git commit' or 'git checkout'$ls/us/lo<TAB># Expands to '/usr/local'# URL autocomplete in browsers"github.com/user/repo"→"https://github.com/user/repo"
# pandas DataFrame - good DWIMimportpandasaspddf=pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})# These all "do what you mean" intuitively:df['A']# Column accessdf[0:2]# Row slicingdf[df['A']>1]# Boolean indexingdf['A']+df['B']# Element-wise addition# Git - good DWIM examplesgitadd.# Add all changed filesgitcommit-am"msg"# Add all and commitgitpush# Push to tracked upstream branchgitcheckoutmain# Switch to main branch
# Examples of hacker aesthetic values:# Elegance - simple, clean solutiondeffactorial(n):return1ifn<=1elsen*factorial(n-1)# vs. verbose alternativedeffactorial_verbose(n):ifn<0:raiseValueError("Negative input not allowed")ifn==0orn==1:return1result=1foriinrange(2,n+1):result=result*ireturnresult# Cleverness - non-obvious but brilliantdefreverse_bits(n):returnint(bin(n)[2:].zfill(32)[::-1],2)# Orthogonality - tools that compose well # Unix philosophy: do one thing wellcatfile.txt|grep"pattern"|sort|uniq-c|head-10
These resources represent different aspects of computing culture and methodology - systematic program design, elegant distributed algorithms, user-centered design philosophy, and the rich cultural history of computing communities. Together they illustrate how technical and cultural evolution intertwine in the computing field.