Download WGU D793 Formal Languages Task 1 and 2 Guide: Programming Paradigms Analysis and Code Con and more Exams Programming Languages in PDF only on Docsity!
WGU D793 Formal Languages Task 1 and 2 Guide: Programming Paradigms
Analysis and Code Conversion from FORTRAN to Python โ 2026 Updated with
complete solutions.
WGU D793 Formal Languages - Complete 60-Page Case Study Guide Task 1 & Task 2: Programming Paradigms Analysis and FORTRAN to Python Conversion PART ONE: EXECUTIVE SUMMARY (Pages 1-3) Course Overview WGU D793 Formal Languages requires students to master two primary competencies:
- Task 1 : Analysis of programming paradigms and their application in language design
- Task 2 : Practical code conversion from legacy FORTRAN to modern Python This comprehensive 60-page case study provides complete solutions, step-by-step methodologies, and ready-to-use code templates for both tasks, updated for the 2026 curriculum. Key Learning Objectives
1.2 The Four Major Paradigms python
ILLUSTRATIVE EXAMPLE: Solving the same problem in four paradigms
IMPERATIVE (FORTRAN style in Python)
def sum_imperative(numbers): total = 0 for i in range(len(numbers)): total = total + numbers[i] return total
FUNCTIONAL
def sum_functional(numbers): return reduce(lambda x, y: x + y, numbers, 0 )
OBJECT-ORIENTED
class SumCalculator: def init(self, numbers): self.numbers = numbers self.total = 0 def calculate(self): self.total = sum(self.numbers) return self.total
DECLARATIVE (using Python's declarative features)
def sum_declarative(numbers): return sum(numbers) # The "what" not the "how" 1.3 Paradigm Comparison Matrix Aspect Imperative Functional OOP Declarative State Management Mutable Immutable Encapsulated Implicit
Primary Abstraction Statements Functions Objects Rules Control Flow Explicit loops Recursion Method calls Pattern matching Side Effects Permitted Discouraged Controlled Avoided FORTRAN Support Native Limited None None Python Support Native Strong Strong Moderate Chapter 2: Deep Dive - The Imperative Paradigm (Pages 9-14) 2.1 FORTRAN as the Quintessential Imperative Language FORTRAN (FORmula TRANslation) was designed in 1957 specifically for scientific computing. Its imperative nature manifests through: Sequential Execution fortran PROGRAM sequential_example IMPLICIT NONE INTEGER :: x, y, z x = 5! Statement 1 y = 10! Statement 2 z = x + y! Statement 3 PRINT *, z! Statement 4 END PROGRAM State Modification fortran SUBROUTINE modify_state(arr, n)
3.1 Core Principles Functional programming treats computation as mathematical function evaluation. Key characteristics: Pure Functions python
Pure function - no side effects, same input = same output
def pure_add(x, y): return x + y
Impure function - modifies external state
counter = 0 def impure_add(x, y): global counter counter += 1 return x + y First-Class Functions python
Functions can be passed as arguments
def apply_operation(operation, x, y): return operation(x, y) result = apply_operation(lambda a, b: a * b, 5 , 3 ) # Returns 15 3.2 Python's Functional Features Feature Syntax Description map() map(func, iterable) Apply function to all items
filter() filter(predicate, iterable) Select items meeting condition reduce() reduce(func, iterable) Accumulate values lambda lambda x: x2 Anonymous functions list comprehensions [x2 for x in list] Declarative list creation Chapter 4: Deep Dive - Object-Oriented Paradigm (Pages 19-22) 4.1 FORTRAN's OOP Limitations Traditional FORTRAN (pre-2003) has no native OOP support. This is a critical distinction for Task 1 analysis. FORTRAN 77 and 90:
- No classes
- No inheritance
- No polymorphism
- No encapsulation beyond module-level 4.2 Python's Comprehensive OOP python class ScientificCalculator: """Demonstrates Python's OOP capabilities""" class_variable = "All instances share this" def init(self, precision= 6 ): self._precision = precision # Encapsulation via naming conventio n
1. Better encapsulation (module vs. class scope) 2. Code reuse (no inheritance in legacy FORTRAN) 3. Error handling (try/except vs. GOTO error handling) 4. Dynamic typing vs. static typing Chapter 5: Complete Paradigm Analysis Template (Pages 23-25) Template for Task 1 Response Use this structured template to analyze any FORTRAN code block: markdown
Code Analysis: [Program Name]
FORTRAN Code:
[Copy the FORTRAN code here] **_Imperative Characteristics Identified:_** _1. [List sequential execution statements] 2. [Identify mutable state variables] 3. [Note explicit loop constructs] 4. [Document GOTO or conditional branches]_ **_Python Implementation Analysis:_** python [Your Python translation] **_Paradigm Comparison:_** Criterion FORTRAN (Imperative) Python Implementation State Management [Describe] [Describe] Control Flow [Describe] [Describe] Data Abstraction [Describe] [Describe] Code Organization [Describe] [Describe] **_Paradigm Shift Observations:_** _[Explain how the Python version could leverage OOP or functional features]_ text --- # PART THREE: TASK 2 - FORTRAN TO PYTHON CONVERSION (Pages 26-55) ## Chapter 6: Complete Conversion Methodology (Pages 26-35) ### 6.1 The Four Conversion Strategies Based on current industry practices, there are four primary approaches to converting FORTRAN to Python [citation:1]: | Strategy | Best For | Complexity | Speed | |----------|----------|------------|-------| | **Manual Translation** | Small programs (<500 lines) | High | Slow | | **f2py Wrapper** | Large numerical codes | Medium | Fast execution | | **Hybrid Approach** | Mixed legacy systems | High | Medium | | **Full Rewrite** | Business-critical apps | Very High | Very Slow | ### 6.2 Strategy 1: Manual Translation - Complete Guide def calculate_sum(arr): """Direct translation of FORTRAN function""" # FORTRAN: temp = 0. temp = 0. # FORTRAN: DO i = 1, n for i in range(len(arr)): # FORTRAN: temp = temp + arr(i) temp += arr[i] # FORTRAN: calculate_sum = temp return temp def main(): # FORTRAN: n = 100 n = 100 # FORTRAN: REAL :: x(100) # Using numpy array for better performance x = np.zeros(n) # FORTRAN: DO i = 1, n for i in range(n): # FORTRAN: x(i) = i * 2. # Note: FORTRAN indexes from 1, Python from 0 x[i] = (i + 1 ) * 2. result = calculate_sum(x) print(f'Sum = {result}') if __name__ == '__main__': main() **_6.3 Syntax Conversion Reference Table_** FORTRAN Construct Python Equivalent Notes DO i=1,10 for i in range(10): Python uses 0-index DO i=1,10,2 for i in range(1, 11, 2): Step parameter IF (x .GT. y) THEN if x > y: Use Python operators ELSE IF elif Combined keyword GOTO label **Avoid** - use functions/loops No direct equivalent SUBROUTINE name() def name(): Functions replace subroutines FUNCTION name() def name(): return Functions return values IMPLICIT NONE Not needed Python is dynamically typed INTEGER :: a(10) a = [0]*10 or np.zeros(10) List or numpy array READ(*,*) var var = input() Console input WRITE(*,*) var print(var) Console output OPEN(unit, file) with open(file) as f: Context manager .AND., .OR., .NOT. and, or, not Logical operators .EQ., .NE., .GT. ==, !=, > Comparison operators **_Chapter 7: Complete Code Conversion Examples (Pages 36-50) 7.1 Example 1: Numerical Integration (Trapezoidal Rule) FORTRAN Source:_** fortran PROGRAM trapezoidal IMPLICIT NONE REAL :: a, b, h, sum, x for i in range( 1 , n): x = a + i * h total += f(x) total *= h print(f'Integral = {total}') return total **_Python Conversion (Functional - Enhanced):_** python def trapezoidal_functional(f, a, b, n): """ Pure functional version - no side effects """ h = (b - a) / n x_values = [a + i * h for i in range(n + 1 )] # Using functional composition result = (f(a) + f(b)) / 2.0 + sum(f(x) for x in x_values[ 1 :- 1 ]) return result * h # Usage result = trapezoidal_functional(lambda x: x** 2 + 2 *x + 1 , 0.0, 1.0, 1000 ) print(f'Integral = {result}') **_Python Conversion (Object-Oriented):_** python class NumericalIntegrator: """Encapsulates integration functionality""" def __init__(self, function, a, b, n= 1000 ): self.function = function self.a = a self.b = b self.n = n self._result = None def compute_trapezoidal(self): h = (self.b - self.a) / self.n total = (self.function(self.a) + self.function(self.b)) / 2. for i in range( 1 , self.n): x = self.a + i * h total += self.function(x) self._result = total * h return self._result @property def result(self): if self._result is None: self.compute_trapezoidal() return self._result class QuadraticFunction: def __call__(self, x): return x** 2 + 2 *x + 1 # Usage integrator = NumericalIntegrator(QuadraticFunction(), 0.0, 1.0, 1000 ) print(f'Integral = {integrator.compute_trapezoidal()}') **_7.2 Example 2: Matrix Operations FORTRAN Source:_** fortran SUBROUTINE matrix_multiply(A, B, C, n) IMPLICIT NONE INTEGER :: n, i, j, k REAL :: A(n,n), B(n,n), C(n,n), temp DO i = 1 , n DO j = 1 , n temp = 0. DO k = 1 , n temp = 0. for k in range(n): temp += A[i][k] * B[k][j] C[i][j] = temp return C **_7.3 Example 3: File Processing FORTRAN Source:_** fortran PROGRAM read_data IMPLICIT NONE INTEGER :: i, n, unit REAL :: values( 100 ) CHARACTER( 100 ) :: filename filename = 'data.txt' OPEN(UNIT= 10 , FILE=filename, STATUS='OLD', ACTION='READ') n = 0 DO i = 1 , 100 READ( 10 , *, IOSTAT=status) values(i) IF (status .NE. 0 ) EXIT n = n + 1 END DO CLOSE( 10 ) PRINT *, 'Read', n, 'values' END PROGRAM **_Python Conversion:_** python def read_data_file(filename='data.txt'): """ Pythonic file reading with context manager Handles errors gracefully values = [] try: with open(filename, 'r') as file: for line in file: # Skip empty lines if line.strip(): values.append(float(line.strip())) except FileNotFoundError: print(f"Error: File '{filename}' not found") return [] except ValueError as e: print(f"Error parsing number: {e}") return [] print(f"Read {len(values)} values") return values **_Chapter 8: Using f2py - The Professional Approach (Pages 51-54) 8.1 Complete f2py Workflow_** _f2py is a NumPy tool that automatically generates Python interfaces for FORTRAN code._ **_Step 1: Prepare FORTRAN Code_** fortran ! saved as scientific.f subroutine integrate_fortran(a, b, n, result) implicit none real, intent(in) :: a, b integer, intent(in) :: n real, intent(out) :: result real :: h, x, sum