arc dsl.metta - trueagi-io/metta-wam GitHub Wiki

;; MeTTa code generated from dsl.py

;; def identity(x: Any) -> Any: ;; """ identity function """ ;; return x

;; $x is any value (became a separate statement)
(= (identity $x $output)
   (match-and &self
     "identity function"
     (var $output $x)))

;; def add(a: Numerical, b: Numerical) -> Numerical: ;; """ addition """ ;; if isinstance(a, int) and isinstance(b, int): ;; return a + b ;; elif isinstance(a, tuple) and isinstance(b, tuple): ;; return (a[0] + b[0], a[1] + b[1]) ;; elif isinstance(a, int) and isinstance(b, tuple): ;; return (a + b[0], a + b[1]) ;; return (a[0] + b, a[1] + b)

;; $a and $b are both integers
(= (add $a $b $output)
   (match-and &self
     "addition"
     (is-int $a)
     (is-int $b)
     (+ $a $b $output)))

;; $a and $b are both tuples
(= (add $a $b $output)
   (match-and &self
     "addition"
     (is-tuple $a)
     (is-tuple $b)
     (tuple-index $a 0 $a0)
     (tuple-index $a 1 $a1)
     (tuple-index $b 0 $b0)
     (tuple-index $b 1 $b1)
     (+ $a0 $b0 $out0)
     (+ $a1 $b1 $out1)
     (make-tuple ($out0 $out1) $output)))

;; $a is an integer and $b is a tuple
(= (add $a $b $output)
   (match-and &self
     "addition"
     (is-int $a)
     (is-tuple $b)
     (tuple-index $b 0 $b0)
     (tuple-index $b 1 $b1)
     (+ $a $b0 $out0)
     (+ $a $b1 $out1)
     (make-tuple ($out0 $out1) $output)))

;; $a is a tuple and $b is an integer
(= (add $a $b $output)
   (match-and &self
     "addition"
     (is-tuple $a)
     (is-int $b)
     (tuple-index $a 0 $a0)
     (tuple-index $a 1 $a1)
     (+ $a0 $b $out0)
     (+ $a1 $b $out1)
     (make-tuple ($out0 $out1) $output)))

;; Fall through case: neither $a nor $b are integers or tuples
(= (add $a $b $output) 
   (match-and &self
     "addition"
     (not (is-int $a))
     (not (is-tuple $a))
     (not (is-int $b))
     (not (is-tuple $b))
     (tuple-index $a 0 $a0)
     (tuple-index $a 1 $a1)
     (+ $a0 $b $out0)
     (+ $a1 $b $out1)
     (make-tuple ($out0 $out1) $output)))

;; def subtract(a: Numerical, b: Numerical) -> Numerical: ;; """ subtraction """ ;; if isinstance(a, int) and isinstance(b, int): ;; return a - b ;; elif isinstance(a, tuple) and isinstance(b, tuple): ;; return (a[0] - b[0], a[1] - b[1]) ;; elif isinstance(a, int) and isinstance(b, tuple): ;; return (a - b[0], a - b[1]) ;; return (a[0] - b, a[1] - b)

;; $a and $b are both integers (no change needed)
(= (subtract $a $b $output)
   (match-and &self
     "subtraction"
     (is-int $a)
     (is-int $b)
     (- $a $b $output)))

;; $a and $b are both tuples (no change needed)
(= (subtract $a $b $output)
   (match-and &self
     "subtraction"
     (is-tuple $a)
     (is-tuple $b)
     (tuple-index $a 0 $a0)
     (tuple-index $a 1 $a1)
     (tuple-index $b 0 $b0)
     (tuple-index $b 1 $b1)
     (- $a0 $b0 $out0)
     (- $a1 $b1 $out1)
     (make-tuple ($out0 $out1) $output)))

;; $a is an integer and $b is a tuple (no change needed)
(= (subtract $a $b $output)
   (match-and &self
     "subtraction"
     (is-int $a)
     (is-tuple $b)
     (tuple-index $b 0 $b0)
     (tuple-index $b 1 $b1)
     (- $a $b0 $out0)
     (- $a $b1 $out1)
     (make-tuple ($out0 $out1) $output)))

;; $a is a tuple and $b is an integer (no change needed)
(= (subtract $a $b $output)
   (match-and &self
     "subtraction"
     (is-tuple $a)
     (is-int $b)
     (tuple-index $a 0 $a0)
     (tuple-index $a 1 $a1)
     (- $a0 $b $out0)
     (- $a1 $b $out1)
     (make-tuple ($out0 $out1) $output)))

;; Fall through case (no change needed)
(= (subtract $a $b $output)
   (match-and &self
     "subtraction"
     (not (is-int $a))
     (not (is-tuple $a))
     (not (is-int $b))
     (not (is-tuple $b))
     (tuple-index $a 0 $a0)
     (tuple-index $a 1 $a1)
     (- $a0 $b $out0)
     (- $a1 $b $out1)
     (make-tuple ($out0 $out1) $output)))

;; def multiply(a: Numerical, b: Numerical) -> Numerical: ;; """ multiplication """ ;; if isinstance(a, int) and isinstance(b, int): ;; return a * b ;; elif isinstance(a, tuple) and isinstance(b, tuple): ;; return (a[0] * b[0], a[1] * b[1]) ;; elif isinstance(a, int) and isinstance(b, tuple): ;; return (a * b[0], a * b[1]) ;; return (a[0] * b, a[1] * b)

;; Case 1: Both $a and $b are integers
(= (multiply $a $b $output)
   (match-and &self
     "multiplication"
     (is-int $a)
     (is-int $b)
     (* $a $b $output)))

;; Case 2: Both $a and $b are tuples
(= (multiply $a $b $output)
   (match-and &self
     "multiplication"
     (is-tuple $a)
     (is-tuple $b)
     (tuple-index $a 0 $a0)
     (tuple-index $a 1 $a1)
     (tuple-index $b 0 $b0)
     (tuple-index $b 1 $b1)
     (* $a0 $b0 $out0)
     (* $a1 $b1 $out1)
     (make-tuple ($out0 $out1) $output)))

;; Case 3: $a is an integer and $b is a tuple
(= (multiply $a $b $output)
   (match-and &self
     "multiplication"
     (is-int $a)
     (is-tuple $b)
     (tuple-index $b 0 $b0)
     (tuple-index $b 1 $b1)
     (* $a $b0 $out0)
     (* $a $b1 $out1)
     (make-tuple ($out0 $out1) $output)))

;; Case 4: $a is a tuple and $b is an integer
(= (multiply $a $b $output)
   (match-and &self
     "multiplication"
     (is-tuple $a)
     (is-int $b)
     (tuple-index $a 0 $a0)
     (tuple-index $a 1 $a1)
     (* $a0 $b $out0)
     (* $a1 $b $out1)
     (make-tuple ($out0 $out1) $output)))

;; Fall through case: Neither $a nor $b is an int or tuple
(= (multiply $a $b $output) 
    (match-and &self
      "multiplication"
      (not (is-int $a))
      (not (is-tuple $a))
      (not (is-int $b))
      (not (is-tuple $b))
      (tuple-index $a 0 $a0)
      (tuple-index $a 1 $a1)
      (* $a0 $b $out0)
      (* $a1 $b $out1)
      (make-tuple ($out0 $out1) $output)))

;; def divide(a: Numerical, b: Numerical) -> Numerical: ;; """ floor division """ ;; if isinstance(a, int) and isinstance(b, int): ;; return a // b ;; elif isinstance(a, tuple) and isinstance(b, tuple): ;; return (a[0] // b[0], a[1] // b[1]) ;; elif isinstance(a, int) and isinstance(b, tuple): ;; return (a // b[0], a // b[1]) ;; return (a[0] // b, a[1] // b)

;; $a and $b are both integers (no change needed)
(= (divide $a $b $output)
   (match-and &self
     "floor division"
     (is-int $a)
     (is-int $b)
     (// $a $b $output)))

;; $a and $b are both tuples (extracted intermediate expressions into separate statements)
(= (divide $a $b $output)
   (match-and &self
     "floor division"
     (is-tuple $a)
     (is-tuple $b)
     (tuple-index $a 0 $a0)
     (tuple-index $a 1 $a1)
     (tuple-index $b 0 $b0)
     (tuple-index $b 1 $b1)
     (// $a0 $b0 $out0)
     (// $a1 $b1 $out1)
     (make-tuple ($out0 $out1) $output)))

;; $a is an integer and $b is a tuple (extracted intermediate expressions into separate statements)
(= (divide $a $b $output)
   (match-and &self
     "floor division"
     (is-int $a)
     (is-tuple $b)
     (tuple-index $b 0 $b0)
     (tuple-index $b 1 $b1)
     (// $a $b0 $out0)
     (// $a $b1 $out1)
     (make-tuple ($out0 $out1) $output)))

;; $a is a tuple and $b is an integer (extracted intermediate expressions into separate statements)
(= (divide $a $b $output)
   (match-and &self
     "floor division"
     (is-tuple $a)
     (is-int $b)
     (tuple-index $a 0 $a0)
     (tuple-index $a 1 $a1)
     (// $a0 $b $out0)
     (// $a1 $b $out1)
     (make-tuple ($out0 $out1) $output)))

;; def invert(n: Numerical) -> Numerical: ;; """ inversion with respect to addition """ ;; return -n if isinstance(n, int) else (-n[0], -n[1])

;; $n is int (became a separate statement)
(= (invert $n $output)
   (match-and &self
     "inversion with respect to addition"
     (is-int $n)
     (- 0 $n $output)))

;; $n is tuple (became a separate statement)
(= (invert $n $output)
   (match-and &self
     "inversion with respect to addition"
     (is-tuple $n)
     (tuple-index $n 0 $n0)
     (tuple-index $n 1 $n1)
     (- 0 $n0 $out0)
     (- 0 $n1 $out1)
     (make-tuple ($out0 $out1) $output)))

;; def even(n: Integer) -> Boolean: ;; """ evenness """ ;; return n % 2 == 0

;; Extracted remainder calculation into a separate statement
(= (even $n $output)
   (match-and &self
     "evenness"
     (% $n 2 $remainder)
     (== $remainder 0 $is-even) ;; Extracted the result of equality check into a separate variable
     (var $output $is-even))) ;; Use the extracted variable

;; def double(n: Numerical) -> Numerical: ;; """ scaling by two """ ;; return n * 2 if isinstance(n, int) else (n[0] * 2, n[1] * 2)

;; $n is int (became a separate statement)
(= (double $n $output)
   (match-and &self
     "scaling by two"
     (is-int $n)
     (* $n 2 $output)))

;; $n is tuple (became a separate statement)
(= (double $n $output)
   (match-and &self
     "scaling by two"
     (is-tuple $n)
     (tuple-index $n 0 $n0)
     (tuple-index $n 1 $n1)
     (* $n0 2 $out0)
     (* $n1 2 $out1)
     (make-tuple ($out0 $out1) $output)))

;; def halve(n: Numerical) -> Numerical: ;; """ scaling by one half """ ;; return n // 2 if isinstance(n, int) else (n[0] // 2, n[1] // 2)

;; $n is int (became a separate statement)
(= (halve $n $output)
   (match-and &self
     "scaling by one half"
     (is-int $n)
     (// $n 2 $output)))

;; $n is tuple (became a separate statement)
(= (halve $n $output)
   (match-and &self
     "scaling by one half"
     (is-tuple $n)
     (tuple-index $n 0 $n0)
     (tuple-index $n 1 $n1)
     (// $n0 2 $out0)
     (// $n1 2 $out1)
     (make-tuple ($out0 $out1) $output)))

;; def flip(b: Boolean) -> Boolean: ;; """ logical not """ ;; return not b

;; Extracted logical not into a separate statement
(= (flip $b $output)
   (match-and &self
     "logical not"
     (not $b $not-result) ;; Extracted the result of not operation into a separate variable
     (var $output $not-result))) ;; Use the extracted variable

;; def equality(a: Any, b: Any) -> Boolean: ;; """ equality """ ;; return a == b

;; Extracted the equality check into a separate statement
(= (equality $a $b $output)
   (match-and &self
     "equality"
     (== $a $b $is-equal) ;; Extracted equality check into a separate variable
     (var $output $is-equal))) ;; Use the extracted variable

;; def contained(value: Any, container: Container) -> Boolean: ;; """ element of """ ;; return value in container

;; $value is found in $container (became a separate statement)
(= (contained $value $container $output)
   (match-and &self
     "element of"
     (length $container $len)
     (match-all &self
       "iterate over container"
       (range 0 $len 1 $i)
       (tuple-index $container $i $element)
       (== $element $value)
       (assign true $output))))
;; $value is not found in $container (became a separate statement)
(= (contained $value $container $output)
   (match-and &self
     "element of"
     (length $container $len)
     (match-all &self
       "iterate over container"
       (range 0 $len 1 $i)
       (tuple-index $container $i $element)
       (== $element $value))
     (not (== $output true))
     (assign false $output)))

;; def combine(a: Container, b: Container) -> Container: ;; """ union """ ;; return type(a)((*a, *b))

;; Extracted $elem-a collection into a separate statement
(= (combine $a $b $output)
   (match-and &self
     "union"
     (type $a $container-type)
     (length $a $len-a)
     (length $b $len-b)
     (match-all &self
       "iterate over elements in a"
       (range 0 $len-a 1 $i)
       (tuple-index $a $i $elem-a)
       (collect $elem-a $elements-a)) ;; Use a separate variable for elements from $a
     (match-all &self
       "iterate over elements in b"
       (range 0 $len-b 1 $j)
       (tuple-index $b $j $elem-b)
       (collect $elem-b $elements-b)) ;; Use a separate variable for elements from $b
     (concat $elements-a $elements-b $elements) ;; Combine elements from $a and $b
     (make-tuple $elements $combined-elements)
     (cast $combined-elements $container-type $output)))

;; def intersection(a: FrozenSet, b: FrozenSet) -> FrozenSet: ;; """ returns the intersection of two containers """ ;; return a & b

;; Extracted the creation of set-a and set-b into separate statements
(= (intersection $a $b $output)
   (match-and &self
     "returns the intersection of two containers"
     (make-set $a $set-a)
     (make-set $b $set-b)
     (length $set-a $len-a)
     (match-all &self
       "iterate over elements in set-a"
       (range 0 $len-a 1 $i)
       (tuple-index $set-a $i $elem)
       (contains $set-b $elem)
       (collect $elem $intersection-elements))
     (make-frozenset $intersection-elements $output)))

;; def difference(a: FrozenSet, b: FrozenSet) -> FrozenSet: ;; """ set difference """ ;; return a - b

;; Extracted set-difference into a separate statement
(= (difference $a $b $output)
   (match-and &self
     "set difference"
     (set-difference $a $b $diff) ;; Extracted intermediate expression
     (var $output $diff))) ;; Use the extracted variable

;; def dedupe(tup: Tuple) -> Tuple: ;; """ remove duplicates """ ;; return tuple((e for i, e in enumerate(tup) if tup.index(e) == i))

(= (dedupe $tup $output)
   (match-and &self
     "remove duplicates"
     (length $tup $len)
     (match-all &self
       "iterate over elements with index"
       (range 0 $len 1 $i)
       (tuple-index $tup $i $e)
       (index $tup $e $first-index)
       (== $i $first-index)
       (collect $e $unique-elements))
     (make-tuple $unique-elements $output)))

;; Extracted index comparison into a separate statement
(= (dedupe $tup $output)
   (match-and &self
     "remove duplicates"
     (length $tup $len)
     (match-all &self
       "iterate over elements with index"
       (range 0 $len 1 $i)
       (tuple-index $tup $i $e)
       (index $tup $e $first-index)
       (== $i $first-index $is-first-index) ;; Extracted comparison result
       (if $is-first-index (collect $e $unique-elements))) ;; Use the extracted variable
     (make-tuple $unique-elements $output)))

;; def order(container: Container, compfunc: Callable) -> Tuple: ;; """ order container by custom key """ ;; return tuple(sorted(container, key=compfunc))

;; Extracted sorted container into a separate statement
(= (order $container $compfunc $output)
   (match-and &self
     "order container by custom key"
     (sorted $container $compfunc $sorted-container)
     (make-tuple $sorted-container $output)))

;; def repeat(item: Any, num: Integer) -> Tuple: ;; """ repetition of item within vector """ ;; return tuple((item for i in range(num)))

;; Extracted $num-1 into a separate statement
(= (repeat $item $num $output)
   (match-and &self
     "repetition of item within vector"
     (- $num 1 $num-1))
;; Iteration over indices became a separate statement
(= (repeat $item $num $output)
   (match-and &self
     "repetition of item within vector"
     (- $num 1 $num-1)
     (match-all &self
       "iterate over indices"
       (range 0 $num-1 1 $i)
       (collect $item $items)))
;; Make tuple from items became a separate statement
(= (repeat $item $num $output)
   (match-and &self
     "repetition of item within vector"
     (- $num 1 $num-1)
     (match-all &self
       "iterate over indices"
       (range 0 $num-1 1 $i)
       (collect $item $items))
     (make-tuple $items $output)))

;; def greater(a: Integer, b: Integer) -> Boolean: ;; """ greater """ ;; return a > b

;; Extracted the greater-than comparison into a separate statement
(= (greater $a $b $output)
   (match-and &self
     "greater"
     (> $a $b $is-greater) ;; Extracted comparison result into a separate variable
     (var $output $is-greater))) ;; Use the extracted variable

;; def size(container: Container) -> Integer: ;; """ cardinality """ ;; return len(container)

;; Extracted length into a separate statement
(= (size $container $output)
   (match-and &self
     "cardinality"
     (length $container $len) ;; Extracted length into a separate statement
     (var $output $len))) ;; Use the extracted variable

;; def merge(containers: ContainerContainer) -> Container: ;; """ merging """ ;; return type(containers)((e for c in containers for e in c))

;; Extracted the type of containers into a separate statement
(= (merge $containers $result)
   (match-and &self
     "merging"
     (type $containers $container-type)
     (length $containers $len)
     (match-all &self
       "iterate over containers"
       (range 0 $len 1 $i)
       (tuple-index $containers $i $c)
       (length $c $len-c)
       (match-all &self
         "iterate over elements in container"
         (range 0 $len-c 1 $j)
         (tuple-index $c $j $e)
         (collect $e $elements)))
     (make-tuple $elements $output)
     (cast $output $container-type $result)))

;; $containers is of a certain type and elements are collected (became a separate statement)
(= (merge $containers $result)
   (match-and &self
     "merging"
     (type $containers $container-type)
     (length $containers $len)
     (match-all &self
       "iterate over containers"
       (range 0 $len 1 $i)
       (tuple-index $containers $i $c)
       (length $c $len-c)
       (match-all &self
         "iterate over elements in container"
         (range 0 $len-c 1 $j)
         (tuple-index $c $j $e)
         (collect $e $elements)))
     (make-tuple $elements $output)))

;; $containers is of a certain type and output is cast to container type (became a separate statement)
(= (merge $containers $result)
   (match-and &self
     "merging"
     (type $containers $container-type)
     (length $containers $len)
     (match-all &self
       "iterate over containers"
       (range 0 $len 1 $i)
       (tuple-index $containers $i $c)
       (length $c $len-c)
       (match-all &self
         "iterate over elements in container"
         (range 0 $len-c 1 $j)
         (tuple-index $c $j $e)
         (collect $e $elements)))
     (make-tuple $elements $output)
     (cast $output $container-type $result)))

;; def maximum(container: IntegerSet) -> Integer: ;; """ maximum """ ;; return max(container, default=0)

;; $container is empty (became a separate statement)
(= (maximum $container $output)
   (match-and &self
     "maximum"
     (is-empty $container)
     (== 0 $output)))

;; $container is not empty (became a separate statement)
(= (maximum $container $output)
   (match-and &self
     "maximum"
     (not (is-empty $container))
     (length $container $len)
     (tuple-index $container 0 $max)
     (match-all &self
       "find maximum"
       (range 1 $len 1 $i)
       (tuple-index $container $i $val)
       (match-and &self
         "compare values"
         (> $val $max)
         (set $val $max))) ;; Extracted the comparison into a separate statement
     (var $output $max)))

;; def minimum(container: IntegerSet) -> Integer: ;; """ minimum """ ;; return min(container, default=0)

;; Extracted unique values into a separate statement
(= (minimum $container $output)
   (match-and &self
     "minimum"
     (make-set $container $unique-values)
     (length $unique-values $len)
     (match-all &self
       "find minimum value"
       (range 0 $len 1 $i)
       (tuple-index $unique-values $i $val)
       (collect $val $values))
     (min $values $min-val)
     (or (not (is-empty $values))
         (== $min-val 0))
     (var $output $min-val)))

;; $values is not empty and min value is zero (became a separate statement)
(= (minimum $container $output)
   (match-and &self
     "minimum"
     (make-set $container $unique-values)
     (length $unique-values $len)
     (match-all &self
       "find minimum value"
       (range 0 $len 1 $i)
       (tuple-index $unique-values $i $val)
       (collect $val $values))
     (min $values $min-val)
     (not (is-empty $values))
     (var $output $min-val)))

;; $values is empty and min value is zero (became a separate statement)
(= (minimum $container $output)
   (match-and &self
     "minimum"
     (make-set $container $unique-values)
     (length $unique-values $len)
     (match-all &self
       "find minimum value"
       (range 0 $len 1 $i)
       (tuple-index $unique-values $i $val)
       (collect $val $values))
     (min $values $min-val)
     (== $min-val 0)
     (var $output $min-val)))

;; def valmax(container: Container, compfunc: Callable) -> Integer: ;; """ maximum by custom function """ ;; return compfunc(max(container, key=compfunc, default=0))

;; Extracted range into a separate statement
(= (valmax $container $compfunc $output)
   (match-and &self
     "maximum by custom function"
     (length $container $len)
     (not (== $len 0))
     (make-tuple (0 -1) $range)
     (range 0 $len 1 $i) ;; Extracted range statement
     (match-all &self
       "find max element by custom function"
       (tuple-index $container $i $element)
       ($compfunc $element $comp-value)
       (make-tuple ($comp-value $element) $comp-element) ;; Extracted make-tuple into a separate statement
       (collect $comp-element $comp-elements)) ;; Use the extracted variable
     (max-by $comp-elements first $max-comp-element)
     (tuple-index $max-comp-element 1 $max-element)
     ($compfunc $max-element $output)))

;; $container is empty (became a separate statement)
(= (valmax $container $compfunc $output)
   (match-and &self
     "maximum by custom function"
     (length $container 0)
     ($compfunc 0 $output)))

;; def valmin(container: Container, compfunc: Callable) -> Integer: ;; """ minimum by custom function """ ;; return compfunc(min(container, key=compfunc, default=0))

;; Extracted length check into a separate statement
(= (valmin $container $compfunc $output)
   (match-and &self
     "minimum by custom function"
     (length $container $len)
     (not (== $len 0))
     (match-all &self
       "find minimum by custom function"
       (range 0 $len 1 $i)
       (tuple-index $container $i $val)
       (apply $compfunc $val $comp-val)
       (make-tuple ($comp-val $val) $comp-val-tuple)
       (collect $comp-val-tuple $comp-val-tuples))
     (min-by $comp-val-tuples first $min-comp-val-tuple)
     (tuple-index $min-comp-val-tuple 1 $min-val)
     (apply $compfunc $min-val $output)))

;; Separate statement for when the container is empty
(= (valmin $container $compfunc $output)
   (match-and &self
     "minimum by custom function when container is empty"
     (length $container $len)
     (== $len 0)
     (apply $compfunc 0 $output)))

;; def argmax(container: Container, compfunc: Callable) -> Any: ;; """ largest item by custom order """ ;; return max(container, key=compfunc)

;; Extracted the comparison value calculation into a separate statement
(= (argmax $container $compfunc $output)
   (match-and &self
     "largest item by custom order"
     (length $container $len)
     (match-all &self
       "iterate over container"
       (range 0 $len 1 $i)
       (tuple-index $container $i $item)
       (call $compfunc $item $comp-value)
       (make-tuple ($comp-value $item) $comp-item)
       (collect $comp-item $comp-items))
     (max-by $comp-items first $max-comp-item)
     (tuple-index $max-comp-item 1 $output)))

;; def argmin(container: Container, compfunc: Callable) -> Any: ;; """ smallest item by custom order """ ;; return min(container, key=compfunc)

;; Extracted computation of $comp-value into a separate statement
(= (argmin $container $compfunc $output)
   (match-and &self
     "smallest item by custom order"
     (length $container $len)
     (match-all &self
       "compute comparison values"
       (range 0 $len 1 $i)
       (tuple-index $container $i $item)
       ($compfunc $item $comp-value) ;; Computation of $comp-value
       (make-tuple ($comp-value $item) $comp-item) ;; Use the extracted $comp-value
       (collect $comp-item $comp-items))
     (min-by $comp-items first $min-comp-item)
     (tuple-index $min-comp-item 1 $output)))

;; def mostcommon(container: Container) -> Any: ;; """ most common item """ ;; return max(set(container), key=container.count)

(= (mostcommon $container $output)
   (match-and &self
     "most common item"
     (make-set $container $unique-items)
     (length $unique-items $len)
     (match-all &self
       "find most common item"
       (range 0 $len 1 $i)
       (tuple-index $unique-items $i $item)
       (count $container $item $count)
       (make-tuple ($count $item) $count-item)
       (collect $count-item $count-items))
     (max-by $count-items first $max-count-item)
     (tuple-index $max-count-item 1 $output)))

;; $container is converted to a set and its length is calculated (became a separate statement)
(= (mostcommon $container $output)
   (match-and &self
     "most common item"
     (make-set $container $unique-items)
     (length $unique-items $len)
     (match-all &self
       "find most common item"
       (range 0 $len 1 $i)
       (tuple-index $unique-items $i $item)
       (count $container $item $count)
       (make-tuple ($count $item) $count-item)
       (collect $count-item $count-items))
     (max-by $count-items first $max-count-item)
     (tuple-index $max-count-item 1 $output)))

;; $container is converted to a set and its length is calculated (became a separate statement)
(= (mostcommon $container $output)
   (match-and &self
     "most common item"
     (make-set $container $unique-items)
     (length $unique-items $len)
     (match-all &self
       "find most common item"
       (range 0 $len 1 $i)
       (tuple-index $unique-items $i $item)
       (count $container $item $count)
       (make-tuple ($count $item) $count-item)
       (collect $count-item $count-items))
     (max-by $count-items first $max-count-item)
     (tuple-index $max-count-item 1 $output)))

;; def leastcommon(container: Container) -> Any: ;; """ least common item """ ;; return min(set(container), key=container.count)

;; Extracted unique items and their length into separate statements
(= (leastcommon $container $output)
   (match-and &self
     "least common item"
     (make-set $container $unique-items)
     (length $unique-items $unique-len)
     (match-all &self
       "find least common item"
       (range 0 $unique-len 1 $i)
       (tuple-index $unique-items $i $item)
       (count $container $item $count)
       (make-tuple ($count $item) $count-item)
       (collect $count-item $count-items))
     (min-by $count-items first $min-count-item)
     (tuple-index $min-count-item 1 $output)))

;; $container is a set and $output is the least common item (became a separate statement)
(= (leastcommon $container $output)
   (match-and &self
     "least common item"
     (make-set $container $unique-items)
     (length $unique-items $unique-len)
     (match-all &self
       "find least common item"
       (range 0 $unique-len 1 $i)
       (tuple-index $unique-items $i $item)
       (count $container $item $count)
       (make-tuple ($count $item) $count-item)
       (collect $count-item $count-items))
     (min-by $count-items first $min-count-item)
     (tuple-index $min-count-item 1 $output)))

;; def initset(value: Any) -> FrozenSet: ;; """ initialize container """ ;; return frozenset({value})

;; Extracted make-frozenset into a separate statement
(= (initset $value $output)
   (match-and &self
     "initialize container"
     (make-frozenset ($value) $frozenset) ;; Extracted frozenset creation
     (var $output $frozenset))) ;; Use the extracted variable

;; def both(a: Boolean, b: Boolean) -> Boolean: ;; """ logical and """ ;; return a and b

;; $a and $b are both booleans and $a and $b are true (became a separate statement)
(= (both $a $b $output)
   (match-and &self
     "logical and"
     (is-boolean $a)
     (is-boolean $b)
     (match-and &self
       "check if both are true"
       (== $a true)
       (== $b true)
       (var $output true))))
;; $a and $b are both booleans and $a or $b is false (became a separate statement)
(= (both $a $b $output)
   (match-and &self
     "logical and"
     (is-boolean $a)
     (is-boolean $b)
     (match-and &self
       "check if either is false"
       (or (== $a false) (== $b false))
       (var $output false))))

;; def either(a: Boolean, b: Boolean) -> Boolean: ;; """ logical or """ ;; return a or b

;; Extracted the logical or operation into a separate statement
(= (either $a $b $output)
   (match-and &self
     "logical or"
     (or $a $b $result) ;; Extracted the result of the or operation into a separate variable
     (var $output $result))) ;; Assigned the extracted result to $output

;; def increment(x: Numerical) -> Numerical: ;; """ incrementing """ ;; return x + 1 if isinstance(x, int) else (x[0] + 1, x[1] + 1)

;; $x is int (became a separate statement)
(= (increment $x $output)
   (match-and &self
     "incrementing"
     (is-int $x)
     (+ $x 1 $output)))

;; $x is tuple (became a separate statement)
(= (increment $x $output)
   (match-and &self
     "incrementing"
     (is-tuple $x)
     (tuple-index $x 0 $x0)
     (tuple-index $x 1 $x1)
     (+ $x0 1 $out0)
     (+ $x1 1 $out1)
     (make-tuple ($out0 $out1) $output)))

;; def decrement(x: Numerical) -> Numerical: ;; """ decrementing """ ;; return x - 1 if isinstance(x, int) else (x[0] - 1, x[1] - 1)

;; $x is int (became a separate statement)
(= (decrement $x $output)
   (match-and &self
     "decrementing"
     (is-int $x)
     (- $x 1 $output)))

;; $x is tuple (became a separate statement)
(= (decrement $x $output)
   (match-and &self
     "decrementing"
     (is-tuple $x)
     (tuple-index $x 0 $x0)
     (tuple-index $x 1 $x1)
     (- $x0 1 $out0)
     (- $x1 1 $out1)
     (make-tuple ($out0 $out1) $output)))

;; def crement(x: Numerical) -> Numerical: ;; """ incrementing positive and decrementing negative """ ;; if isinstance(x, int): ;; return 0 if x == 0 else x + 1 if x > 0 else x - 1 ;; return (0 if x[0] == 0 else x[0] + 1 if x[0] > 0 else x[0] - 1, 0 if x[1] == 0 else x[1] + 1 if x[1] > 0 else x[1] - 1)

;; $x is int and zero (became a separate statement)
(= (crement $x $output)
   (match-and &self
     "incrementing positive and decrementing negative"
     (is-int $x)
     (== $x 0 $zero)
     (if $zero
         (var $output 0))))

;; $x is int and positive (became a separate statement)
(= (crement $x $output)
   (match-and &self
     "incrementing positive and decrementing negative"
     (is-int $x)
     (== $x 0 $zero)
     (not $zero)
     (> $x 0)
     (+ $x 1 $output)))

;; $x is int and negative (became a separate statement)
(= (crement $x $output)
   (match-and &self
     "incrementing positive and decrementing negative"
     (is-int $x)
     (== $x 0 $zero)
     (not $zero)
     (< $x 0)
     (- $x 1 $output)))

;; $x is tuple, first element is zero (became a separate statement)
(= (crement $x $output)
   (match-and &self
     "incrementing positive and decrementing negative"
     (is-tuple $x)
     (tuple-index $x 0 $x0)
     (tuple-index $x 1 $x1)
     (== $x0 0 $zero0)
     (if $zero0
         (var $out0 0))
     (== $x1 0 $zero1)
     (if $zero1
         (var $out1 0))
     (make-tuple ($out0 $out1) $output)))

;; $x is tuple, first element is positive (became a separate statement)
(= (crement $x $output)
   (match-and &self
     "incrementing positive and decrementing negative"
     (is-tuple $x)
     (tuple-index $x 0 $x0)
     (tuple-index $x 1 $x1)
     (== $x0 0 $zero0)
     (not $zero0)
     (> $x0 0)
     (+ $x0 1 $out0)
     (== $x1 0 $zero1)
     (if $zero1
         (var $out1 0))
     (make-tuple ($out0 $out1) $output)))

;; $x is tuple, first element is negative (became a separate statement)
(= (crement $x $output)
   (match-and &self
     "incrementing positive and decrementing negative"
     (is-tuple $x)
     (tuple-index $x 0 $x0)
     (tuple-index $x 1 $x1)
     (== $x0 0 $zero0)
     (not $zero0)
     (< $x0 0)
     (- $x0 1 $out0)
     (== $x1 0 $zero1)
     (if $zero1
         (var $out1 0))
     (make-tuple ($out0 $out1) $output)))

;; $x is tuple, second element is positive (became a separate statement)
(= (crement $x $output)
   (match-and &self
     "incrementing positive and decrementing negative"
     (is-tuple $x)
     (tuple-index $x 0 $x0)
     (tuple-index $x 1 $x1)
     (== $x0 0 $zero0)
     (if $zero0
         (var $out0 0))
     (== $x1 0 $zero1)
     (not $zero1)
     (> $x1 0)
     (+ $x1 1 $out1)
     (make-tuple ($out0 $out1) $output)))

;; $x is tuple, second element is negative (became a separate statement)
(= (crement $x $output)
   (match-and &self
     "incrementing positive and decrementing negative"
     (is-tuple $x)
     (tuple-index $x 0 $x0)
     (tuple-index $x 1 $x1)
     (== $x0 0 $zero0)
     (if $zero0
         (var $out0 0))
     (== $x1 0 $zero1)
     (not $zero1)
     (< $x1 0)
     (- $x1 1 $out1)
     (make-tuple ($out0 $out1) $output)))

;; def sign(x: Numerical) -> Numerical: ;; """ sign """ ;; if isinstance(x, int): ;; return 0 if x == 0 else 1 if x > 0 else -1 ;; return (0 if x[0] == 0 else 1 if x[0] > 0 else -1, 0 if x[1] == 0 else 1 if x[1] > 0 else -1)

;; $x is int and zero (became a separate statement)
(= (sign $x $output)
   (match-and &self
     "sign"
     (is-int $x)
     (== $x 0 $zero)
     (not $zero)
     (== $x 0 $output)))

;; $x is int and positive (became a separate statement)
(= (sign $x $output)
   (match-and &self
     "sign"
     (is-int $x)
     (> $x 0 $positive)
     (not $positive)
     (== $x 1 $output)))

;; $x is int and negative (became a separate statement)
(= (sign $x $output)
   (match-and &self
     "sign"
     (is-int $x)
     (< $x 0 $negative)
     (not $negative)
     (== $x -1 $output)))

;; $x is not int and zero (became a separate statement)
(= (sign $x $output)
   (match-and &self
     "sign"
     (not (is-int $x))
     (tuple-index $x 0 $x0)
     (tuple-index $x 1 $x1)
     (== $x0 0 $zero0)
     (not $zero0)
     (== $x0 0 $out0)
     (== $x1 0 $zero1)
     (not $zero1)
     (== $x1 0 $out1)
     (make-tuple ($out0 $out1) $output)))

;; $x is not int and positive (became a separate statement)
(= (sign $x $output)
   (match-and &self
     "sign"
     (not (is-int $x))
     (tuple-index $x 0 $x0)
     (tuple-index $x 1 $x1)
     (> $x0 0 $positive0)
     (not $positive0)
     (== $x0 1 $out0)
     (> $x1 0 $positive1)
     (not $positive1)
     (== $x1 1 $out1)
     (make-tuple ($out0 $out1) $output)))

;; $x is not int and negative (became a separate statement)
(= (sign $x $output)
   (match-and &self
     "sign"
     (not (is-int $x))
     (tuple-index $x 0 $x0)
     (tuple-index $x 1 $x1)
     (< $x0 0 $negative0)
     (not $negative0)
     (== $x0 -1 $out0)
     (< $x1 0 $negative1)
     (not $negative1)
     (== $x1 -1 $out1)
     (make-tuple ($out0 $out1) $output)))

;; def positive(x: Integer) -> Boolean: ;; """ positive """ ;; return x > 0

;; Extracted comparison into a separate statement
(= (positive $x $output)
   (match-and &self
     "positive"
     (> $x 0 $is-positive) ;; Extracted the comparison result into $is-positive
     (var $output $is-positive))) ;; Use the extracted variable

;; def toivec(i: Integer) -> IntegerTuple: ;; """ vector pointing vertically """ ;; return (i, 0)

;; Extracted the tuple creation into a separate statement
(= (toivec $i $output)
   (match-and &self
     "vector pointing vertically"
     (make-tuple ($i 0) $vec) ;; Extracted vector into a separate statement
     (var $output $vec))) ;; Use the extracted variable

;; def tojvec(j: Integer) -> IntegerTuple: ;; """ vector pointing horizontally """ ;; return (0, j)

;; Extracted the tuple creation into a separate statement
(= (tojvec $j $output)
   (match-and &self
     "vector pointing horizontally"
     (make-tuple (0 $j) $temp-tuple) ;; Created a temporary variable for the tuple
     (var $output $temp-tuple))) ;; Assigned the temporary variable to $output

;; def sfilter(container: Container, condition: Callable) -> Container: ;; """ keep elements in container that satisfy condition """ ;; return type(container)((e for e in container if condition(e)))

;; Extracted condition check into a separate statement
(= (sfilter $container $condition $output)
   (match-and &self
     "keep elements in container that satisfy condition"
     (type $container $container-type)
     (length $container $len)
     (match-all &self
       "iterate over elements in container"
       (range 0 $len 1 $i)
       (tuple-index $container $i $e)
       (condition $e $satisfies)
       (if $satisfies
           (collect $e $filtered-elements))))
     (make-tuple $filtered-elements $filtered-tuple)
     (cast $filtered-tuple $container-type $output)))

;; $container is of a specific type and elements satisfy condition (became a separate statement)
(= (sfilter $container $condition $output)
   (match-and &self
     "keep elements in container that satisfy condition"
     (type $container $container-type)
     (length $container $len)
     (match-all &self
       "iterate over elements in container"
       (range 0 $len 1 $i)
       (tuple-index $container $i $e)
       (condition $e $satisfies)
       (if $satisfies
           (collect $e $filtered-elements))))
     (make-tuple $filtered-elements $filtered-tuple)
     (cast $filtered-tuple $container-type $output)))

;; def mfilter(container: Container, function: Callable) -> FrozenSet: ;; """ filter and merge """ ;; return merge(sfilter(container, function))

;; Extracted sfilter result into a separate statement
(= (mfilter $container $function $output)
   (match-and &self
     "filter and merge"
     (sfilter $container $function $filtered)
     (merge $filtered $output)))

;; def extract(container: Container, condition: Callable) -> Any: ;; """ first element of container that satisfies condition """ ;; return next((e for e in container if condition(e)))

;; Extracted condition check into a separate statement
(= (extract $container $condition $output)
   (match-and &self
     "first element of container that satisfies condition"
     (length $container $len)
     (match-all &self
       "iterate over elements"
       (range 0 $len 1 $i)
       (tuple-index $container $i $e)
       (condition $e $satisfies)
       (if $satisfies
           (collect $e $result))))
     (tuple-index $result 0 $output)))

;; $container has elements that satisfy the condition (became a separate statement)
(= (extract $container $condition $output)
   (match-and &self
     "first element of container that satisfies condition"
     (length $container $len)
     (match-all &self
       "iterate over elements"
       (range 0 $len 1 $i)
       (tuple-index $container $i $e)
       (condition $e $satisfies)
       (if $satisfies
           (collect $e $result))))
     (tuple-index $result 0 $output)))

;; $container has no elements that satisfy the condition (became a separate statement)
(= (extract $container $condition $output)
   (match-and &self
     "first element of container that satisfies condition"
     (length $container $len)
     (match-all &self
       "iterate over elements"
       (range 0 $len 1 $i)
       (tuple-index $container $i $e)
       (condition $e $satisfies)
       (if $satisfies
           (collect $e $result))))
     (tuple-index $result 0 $output)))

;; def totuple(container: FrozenSet) -> Tuple: ;; """ conversion to tuple """ ;; return tuple(container)

;; Extracted the make-tuple operation into a separate statement
(= (totuple $container $output)
   (match-and &self
     "conversion to tuple"
     (make-tuple $container $temp-output) ;; Extracted intermediate expression
     (var $output $temp-output))) ;; Assigned the extracted variable to $output

;; def first(container: Container) -> Any: ;; """ first item of container """ ;; return next(iter(container))

;; Extracted iterator into a separate statement
(= (first $container $output)
   (match-and &self
     "first item of container"
     (iter $container $iterator)
     (next $iterator $first-item) ;; Extracted first item into a separate statement
     (var $output $first-item))) ;; Use the extracted variable

;; def last(container: Container) -> Any: ;; """ last item of container """ ;; return max(enumerate(container))[1]

;; Extracted last index into a separate statement
(= (last $container $output)
   (match-and &self
     "last item of container"
     (length $container $len)
     (- $len 1 $last-index)
     (tuple-index $container $last-index $last-item) ;; Extracted last item into a separate statement
     (var $output $last-item))) ;; Use the extracted variable

;; def insert(value: Any, container: FrozenSet) -> FrozenSet: ;; """ insert item into container """ ;; return container.union(frozenset({value}))

;; Extracted the creation of $value-set into a separate statement
(= (insert $value $container $output)
   (match-and &self
     "insert item into container"
     (make-frozenset ($value) $value-set)
     (union $container $value-set $output)))

;; def remove(value: Any, container: Container) -> Container: ;; """ remove item from container """ ;; return type(container)((e for e in container if e != value))

;; Extracted type of container into a separate statement
(= (remove $value $container $output)
   (match-and &self
     "remove item from container"
     (type $container $container-type)
     (length $container $len)
     (match-all &self
       "iterate over elements in container"
       (range 0 $len 1 $i)
       (tuple-index $container $i $e)
       (not (== $e $value))
       (collect $e $filtered-elements))
     (make-tuple $filtered-elements $filtered-tuple)
     (cast $filtered-tuple $container-type $output)))

;; $container is a tuple and $value is not in it (became a separate statement)
(= (remove $value $container $output)
   (match-and &self
     "remove item from container"
     (type $container $container-type)
     (length $container $len)
     (match-all &self
       "iterate over elements in container"
       (range 0 $len 1 $i)
       (tuple-index $container $i $e)
       (not (== $e $value))
       (collect $e $filtered-elements))
     (make-tuple $filtered-elements $filtered-tuple)
     (cast $filtered-tuple $container-type $output)))

;; def other(container: Container, value: Any) -> Any: ;; """ other value in the container """ ;; return first(remove(value, container))

;; Extracted the removal of the value into a separate statement
(= (other $container $value $output)
   (match-and &self
     "other value in the container"
     (remove $value $container $removed)
     (first $removed $first-removed) ;; Extracted first element into a separate statement
     (var $output $first-removed))) ;; Use the extracted variable

;; def interval(start: Integer, stop: Integer, step: Integer) -> Tuple: ;; """ range """ ;; return tuple(range(start, stop, step))

;; Extracted range into a separate statement
(= (interval $start $stop $step $output)
   (match-and &self
     "range"
     (range $start $stop $step $indices)
     (make-tuple $indices $output)))

;; def astuple(a: Integer, b: Integer) -> IntegerTuple: ;; """ constructs a tuple """ ;; return (a, b)

;; Extracted tuple construction into a separate statement
(= (astuple $a $b $output)
   (match-and &self
     "constructs a tuple"
     (make-tuple ($a $b) $temp-tuple) ;; Created a temporary variable for the tuple
     (var $output $temp-tuple))) ;; Assigned the temporary variable to $output

;; def product(a: Container, b: Container) -> FrozenSet: ;; """ cartesian product """ ;; return frozenset(((i, j) for j in b for i in a))

;; Extracted tuple-index $b $j into a separate statement
(= (product $a $b $output)
   (match-and &self
     "cartesian product"
     (length $a $len-a)
     (length $b $len-b)
     (match-all &self
       "iterate over elements in b"
       (range 0 $len-b 1 $j)
       (tuple-index $b $j $bj) ;; Extracted $bj
       (match-all &self
         "iterate over elements in a"
         (range 0 $len-a 1 $i)
         (tuple-index $a $i $ai) ;; Extracted $ai
         (make-tuple ($ai $bj) $pair) ;; Use the extracted variables
         (collect $pair $pairs)))
     (make-frozenset $pairs $output)))

;; def pair(a: Tuple, b: Tuple) -> TupleTuple: ;; """ zipping of two tuples """ ;; return tuple(zip(a, b))

(= (pair $a $b $output)
   (match-and &self
     "zipping of two tuples"
     (length $a $len-a)
     (length $b $len-b)
     (min $len-a $len-b $min-len)
     (match-all &self
       "iterate over indices"
       (range 0 $min-len 1 $i)
       (tuple-index $a $i $val-a)
       (tuple-index $b $i $val-b)
       (make-tuple ($val-a $val-b) $pair)
       (collect $pair $pairs))
     (make-tuple $pairs $output))) ;; No changes needed for this function as there are no nested function calls or multiple assignments to $output

;; def branch(condition: Boolean, a: Any, b: Any) -> Any: ;; """ if else branching """ ;; return a if condition else b

;; $condition is true (became a separate statement)
(= (branch $condition $a $b $output)
   (match-and &self
     "if else branching"
     (== $condition true)
     (var $output $a)))

;; $condition is false (became a separate statement)
(= (branch $condition $a $b $output)
   (match-and &self
     "if else branching"
     (== $condition false)
     (var $output $b)))

;; def compose(outer: Callable, inner: Callable) -> Callable: ;; """ function composition """ ;; return lambda x: outer(inner(x))

;; Extracted inner function application into a separate statement
(= (lambda-helper $outer $inner $x $inner-result)
   (match-and &self
     "apply inner function"
     ($inner $x $inner-result)))

;; Extracted outer function application into a separate statement
(= (lambda-helper $outer $inner-result $result)
   (match-and &self
     "apply outer function"
     ($outer $inner-result $result)))

;; Composed function with separate statements for inner and outer applications
(= (compose $outer $inner $output)
   (match-and &self
     "function composition"
     (lambda-helper $outer $inner $x $inner-result)
     (lambda-helper $outer $inner-result $output)))

;; def chain(h: Callable, g: Callable, f: Callable) -> Callable: ;; """ function composition with three functions """ ;; return lambda x: h(g(f(x)))

;; Extracted make-lambda into a separate statement
(= (chain $h $g $f $output)
   (match-and &self
     "function composition with three functions"
     (make-lambda (lambda-helper $h $g $f) $lambda)
     (var $output $lambda))) ;; Use the extracted variable

;; Extracted intermediate expressions into separate statements
(= (lambda-helper $h $g $f $x $result)
   (match-and &self
     "apply composed functions"
     (f $x $fx)
     (g $fx $gfx)
     (h $gfx $result)))

;; def matcher(function: Callable, target: Any) -> Callable: ;; """ construction of equality function """ ;; return lambda x: function(x) == target

;; Extracted make-lambda into a separate statement
(= (matcher $function $target $output)
   (match-and &self
     "construction of equality function"
     (lambda-helper $function $target $lambda-helper-output) ;; Extracted lambda-helper result into a separate statement
     (make-lambda $lambda-helper-output $output))) ;; Use the extracted variable

;; Extracted function call and equality check into separate statements
(= (lambda-helper $function $target $x $out)
   (match-and &self
     "check equality"
     ($function $x $fx) ;; Extracted function call into a separate statement
     (== $fx $target $out))) ;; Use the extracted variable

;; def rbind(function: Callable, fixed: Any) -> Callable: ;; """ fix the rightmost argument """ ;; n = function.code.co_argcount ;; if n == 2: ;; return lambda x: function(x, fixed) ;; elif n == 3: ;; return lambda x, y: function(x, y, fixed) ;; else: ;; return lambda x, y, z: function(x, y, z, fixed)

;; Extracted argcount into a separate statement
;; Separated cases based on the number of arguments
(= (rbind $function $fixed $output)
   (match-and &self
     "fix the rightmost argument"
     (argcount $function $n)
     (is-equal $n 2)
     (make-lambda (lambda-helper-2 $function $fixed) $output)))

(= (rbind $function $fixed $output)
   (match-and &self
     "fix the rightmost argument"
     (argcount $function $n)
     (is-equal $n 3)
     (make-lambda (lambda-helper-3 $function $fixed) $output)))

(= (rbind $function $fixed $output)
   (match-and &self
     "fix the rightmost argument"
     (argcount $function $n)
     (not (is-equal $n 2))
     (not (is-equal $n 3))
     (make-lambda (lambda-helper-4 $function $fixed) $output)))

;; No changes needed for lambda-helper functions as they are already simple
(= (lambda-helper-2 $function $fixed $x $out)
   (match-and &self
     "apply function with fixed rightmost argument"
     ($function $x $fixed $out)))

(= (lambda-helper-3 $function $fixed $x $y $out)
   (match-and &self
     "apply function with fixed rightmost argument"
     ($function $x $y $fixed $out)))

(= (lambda-helper-4 $function $fixed $x $y $z $out)
   (match-and &self
     "apply function with fixed rightmost argument"
     ($function $x $y $z $fixed $out)))

;; def lbind(function: Callable, fixed: Any) -> Callable: ;; """ fix the leftmost argument """ ;; n = function.code.co_argcount ;; if n == 2: ;; return lambda y: function(fixed, y) ;; elif n == 3: ;; return lambda y, z: function(fixed, y, z) ;; else: ;; return lambda y, z, a: function(fixed, y, z, a)

;; $n is 2 (became a separate statement)
(= (lbind $function $fixed $output)
   (match-and &self
     "fix the leftmost argument"
     (argcount $function $n)
     (match-and &self
       "case for two arguments"
       (== $n 2)
       (make-lambda (lambda-helper-2 $function $fixed) $output))))

;; $n is 3 (became a separate statement)
(= (lbind $function $fixed $output)
   (match-and &self
     "fix the leftmost argument"
     (argcount $function $n)
     (match-and &self
       "case for three arguments"
       (== $n 3)
       (make-lambda (lambda-helper-3 $function $fixed) $output))))

;; $n is not 2 or 3 (became a separate statement)
(= (lbind $function $fixed $output)
   (match-and &self
     "fix the leftmost argument"
     (argcount $function $n)
     (match-and &self
       "case for four arguments"
       (not (== $n 2))
       (not (== $n 3))
       (make-lambda (lambda-helper-4 $function $fixed) $output))))

(= (lambda-helper-2 $function $fixed $y $out)
   (match-and &self
     "lambda for two arguments"
     ($function $fixed $y $out)))

(= (lambda-helper-3 $function $fixed $y $z $out)
   (match-and &self
     "lambda for three arguments"
     ($function $fixed $y $z $out)))

(= (lambda-helper-4 $function $fixed $y $z $a $out)
   (match-and &self
     "lambda for four arguments"
     ($function $fixed $y $z $a $out)))

;; def power(function: Callable, n: Integer) -> Callable: ;; """ power of function """ ;; if n == 1: ;; return function ;; return compose(function, power(function, n - 1))

;; $n is 1 (became a separate statement)
(= (power $function $n $output)
   (match-and &self
     "power of function"
     (== $n 1)
     (var $output $function)))

;; $n is not 1 (became a separate statement)
(= (power $function $n $output)
   (match-and &self
     "power of function"
     (not (== $n 1))
     (- $n 1 $n-1)
     (power $function $n-1 $recursive-result)
     (compose $function $recursive-result $output)))

;; def fork(outer: Callable, a: Callable, b: Callable) -> Callable: ;; """ creates a wrapper function """ ;; return lambda x: outer(a(x), b(x))

;; Extracted make-lambda into a separate statement
(= (fork $outer $a $b $output)
   (match-and &self
     "creates a wrapper function"
     (make-lambda fork-helper $outer $a $b $lambda) ;; Extracted lambda creation
     (var $output $lambda))) ;; Use the extracted variable

;; Extracted intermediate expressions into separate statements
(= (fork-helper $outer $a $b $x $result)
   (match-and &self
     "apply outer to results of a and b"
     ($a $x $result-a)
     ($b $x $result-b)
     ($outer $result-a $result-b $outer-result) ;; Extracted outer application
     (var $result $outer-result))) ;; Use the extracted variable

;; def apply(function: Callable, container: Container) -> Container: ;; """ apply function to each item in container """ ;; return type(container)((function(e) for e in container))

;; Extracted type and length into separate statements
(= (apply $function $container $output)
   (match-and &self
     "apply function to each item in container"
     (type $container $container-type)
     (length $container $len)
     (match-all &self
       "iterate over elements in container"
       (range 0 $len 1 $i)
       (tuple-index $container $i $e)
       (apply $function $e $result)
       (collect $result $results))
     (make-tuple $results $temp-output) ;; Extracted intermediate output into a separate statement
     (cast $temp-output $container-type $output))) ;; Use the extracted variable

;; def rapply(functions: Container, value: Any) -> Container: ;; """ apply each function in container to value """ ;; return type(functions)((function(value) for function in functions))

;; Extracted container type and length into separate statements
(= (rapply $functions $value $output)
   (match-and &self
     "apply each function in container to value"
     (type $functions $container-type)
     (length $functions $len)
     (match-all &self
       "iterate over functions"
       (range 0 $len 1 $i)
       (tuple-index $functions $i $function)
       (apply $function $value $result)
       (collect $result $results))
     (make-tuple $results $intermediate-output) ;; Extracted intermediate output
     (cast $intermediate-output $container-type $output))) ;; Use the extracted variable

;; def mapply(function: Callable, container: ContainerContainer) -> FrozenSet: ;; """ apply and merge """ ;; return merge(apply(function, container))

;; Extracted the result of apply into a separate statement
(= (mapply $function $container $output)
   (match-and &self
     "apply and merge"
     (apply $function $container $applied)
     (merge $applied $output))) ;; No change needed here as the code is already in its simplest form

;; def papply(function: Callable, a: Tuple, b: Tuple) -> Tuple: ;; """ apply function on two vectors """ ;; return tuple((function(i, j) for i, j in zip(a, b)))

(= (papply $function $a $b $output)
   (match-and &self
     "apply function on two vectors"
     (length $a $len-a)
     (length $b $len-b)
     (== $len-a $len-b)
     (match-all &self
       "iterate over pairs"
       (range 0 $len-a 1 $i)
       (tuple-index $a $i $ai)
       (tuple-index $b $i $bi)
       (function $ai $bi $result)
       (collect $result $results))
     (make-tuple $results $output))) ;; No changes needed here as there are no nested function calls or multiple assignments to $output

;; def mpapply(function: Callable, a: Tuple, b: Tuple) -> Tuple: ;; """ apply function on two vectors and merge """ ;; return merge(papply(function, a, b))

;; Extracted papply-result into a separate statement
(= (mpapply $function $a $b $output)
   (match-and &self
     "apply function on two vectors and merge"
     (papply $function $a $b $papply-result)
     (merge $papply-result $output)))

;; def prapply(function, a: Container, b: Container) -> FrozenSet: ;; """ apply function on cartesian product """ ;; return frozenset((function(i, j) for j in b for i in a))

;; Extracted tuple-index for $b into a separate statement
(= (prapply $function $a $b $output)
   (match-and &self
     "apply function on cartesian product"
     (length $a $len-a)
     (length $b $len-b)
     (match-all &self
       "iterate over elements in b"
       (range 0 $len-b 1 $j)
       (tuple-index $b $j $bj)
       (match-all &self
         "iterate over elements in a"
         (range 0 $len-a 1 $i)
         (tuple-index $a $i $ai)
         (apply $function $ai $bj $result)
         (collect $result $results)))
     (make-frozenset $results $output)))

;; def mostcolor(element: Element) -> Integer: ;; """ most common color """ ;; values = [v for r in element for v in r] if isinstance(element, tuple) else [v for v, _ in element] ;; return max(set(values), key=values.count)

;; $element is a tuple (became a separate statement)
(= (mostcolor $element $output)
   (match-and &self
     "most common color"
     (is-tuple $element)
     (length $element $len)
     (match-all &self
       "iterate over rows"
       (range 0 $len 1 $i)
       (tuple-index $element $i $r)
       (length $r $len-r)
       (match-all &self
         "iterate over values in row"
         (range 0 $len-r 1 $j)
         (tuple-index $r $j $v)
         (collect $v $values))))
     (make-set $values $unique-values)
     (length $unique-values $unique-len)
     (match-all &self
       "find most common color"
       (range 0 $unique-len 1 $k)
       (tuple-index $unique-values $k $val)
       (count $values $val $count)
       (make-tuple ($count $val) $count-val)
       (collect $count-val $count-values))
     (max-by $count-values first $max-count-val)
     (tuple-index $max-count-val 1 $output)))

;; $element is not a tuple (became a separate statement)
(= (mostcolor $element $output)
   (match-and &self
     "most common color"
     (not (is-tuple $element))
     (length $element $len)
     (match-all &self
       "iterate over element pairs"
       (range 0 $len 1 $i)
       (tuple-index $element $i $pair)
       (tuple-index $pair 0 $v)
       (collect $v $values)))
     (make-set $values $unique-values)
     (length $unique-values $unique-len)
     (match-all &self
       "find most common color"
       (range 0 $unique-len 1 $k)
       (tuple-index $unique-values $k $val)
       (count $values $val $count)
       (make-tuple ($count $val) $count-val)
       (collect $count-val $count-values))
     (max-by $count-values first $max-count-val)
     (tuple-index $max-count-val 1 $output)))

;; def leastcolor(element: Element) -> Integer: ;; """ least common color """ ;; values = [v for r in element for v in r] if isinstance(element, tuple) else [v for v, _ in element] ;; return min(set(values), key=values.count)

;; Extracted length of element into a separate statement
(= (leastcolor $element $output)
   (match-and &self
     "least common color"
     (is-tuple $element)
     (length $element $len)
     (match-all &self
       "iterate over rows"
       (range 0 $len 1 $i)
       (tuple-index $element $i $r)
       (length $r $len-r)
       (match-all &self
         "iterate over values in row"
         (range 0 $len-r 1 $j)
         (tuple-index $r $j $v)
         (collect $v $values))))
     ;; Extracted length of element into a separate statement
     (not (is-tuple $element))
     (length $element $len)
     (match-all &self
       "iterate over element pairs"
       (range 0 $len 1 $i)
       (tuple-index $element $i $pair)
       (tuple-index $pair 0 $v)
       (collect $v $values)))
     ;; Extracted unique values into a separate statement
     (make-set $values $unique-values)
     (length $unique-values $unique-len)
     (match-all &self
       "find least common color"
       (range 0 $unique-len 1 $k)
       (tuple-index $unique-values $k $val)
       (count $values $val $count)
       (make-tuple ($count $val) $count-val)
       (collect $count-val $count-values))
     ;; Extracted minimum count value into a separate statement
     (min-by $count-values first $min-count-val)
     (tuple-index $min-count-val 1 $output)))

;; def height(piece: Piece) -> Integer: ;; """ height of grid or patch """ ;; if len(piece) == 0: ;; return 0 ;; if isinstance(piece, tuple): ;; return len(piece) ;; return lowermost(piece) - uppermost(piece) + 1

;; $piece is empty (became a separate statement)
(= (height $piece $output)
   (match-and &self
     "height of grid or patch"
     (length $piece 0)
     (var $output 0)))

;; $piece is a tuple (became a separate statement)
(= (height $piece $output)
   (match-and &self
     "height of grid or patch"
     (is-tuple $piece)
     (length $piece $output)))

;; $piece is not a tuple (became a separate statement)
(= (height $piece $output)
   (match-and &self
     "height of grid or patch"
     (not (is-tuple $piece))
     (lowermost $piece $lowermost)
     (uppermost $piece $uppermost)
     (- $lowermost $uppermost $diff)
     (+ $diff 1 $output)))

;; def width(piece: Piece) -> Integer: ;; """ width of grid or patch """ ;; if len(piece) == 0: ;; return 0 ;; if isinstance(piece, tuple): ;; return len(piece[0]) ;; return rightmost(piece) - leftmost(piece) + 1

;; $piece is empty (became a separate statement)
(= (width $piece $output)
   (match-and &self
     "width of grid or patch"
     (length $piece $len)
     (== $len 0)
     (var $output 0)))

;; $piece is a non-empty tuple (became a separate statement)
(= (width $piece $output)
   (match-and &self
     "width of grid or patch"
     (not (== (length $piece) 0))
     (is-tuple $piece)
     (tuple-index $piece 0 $first-row)
     (length $first-row $output)))

;; $piece is non-empty and not a tuple (became a separate statement)
(= (width $piece $output)
   (match-and &self
     "width of grid or patch"
     (not (== (length $piece) 0))
     (not (is-tuple $piece))
     (rightmost $piece $right)
     (leftmost $piece $left)
     (- $right $left $diff)
     (+ $diff 1 $output)))

;; def shape(piece: Piece) -> IntegerTuple: ;; """ height and width of grid or patch """ ;; return (height(piece), width(piece))

;; Extracted height and width into separate statements
(= (shape $piece $output)
   (match-and &self
     "height and width of grid or patch"
     (height $piece $height)
     (width $piece $width)
     (make-tuple ($height $width) $dimensions) ;; Extracted dimensions into a separate statement
     (var $output $dimensions))) ;; Use the extracted variable

;; def portrait(piece: Piece) -> Boolean: ;; """ whether height is greater than width """ ;; return height(piece) > width(piece)

;; Extracted height and width comparisons into separate statements
(= (portrait $piece $output)
   (match-and &self
     "whether height is greater than width"
     (height $piece $height)
     (width $piece $width)
     (> $height $width $is-portrait) ;; Extracted the comparison result into a temporary variable
     (var $output $is-portrait))) ;; Assigned the temporary variable to $output

;; def colorcount(element: Element, value: Integer) -> Integer: ;; """ number of cells with color """ ;; if isinstance(element, tuple): ;; return sum((row.count(value) for row in element)) ;; return sum((v == value for v, _ in element))

;; $element is a tuple (became a separate statement)
(= (colorcount $element $value $output)
   (match-and &self
     "number of cells with color"
     (is-tuple $element)
     (length $element $len)
     (match-all &self
       "iterate over rows"
       (range 0 $len 1 $i)
       (tuple-index $element $i $row)
       (count $row $value $count)
       (collect $count $counts))
     (sum $counts $output)))

;; $element is not a tuple (became a separate statement)
(= (colorcount $element $value $output)
   (match-and &self
     "number of cells with color"
     (not (is-tuple $element))
     (length $element $len)
     (match-all &self
       "iterate over element pairs"
       (range 0 $len 1 $i)
       (tuple-index $element $i $pair)
       (tuple-index $pair 0 $v)
       (== $v $value $is-equal)
       (if $is-equal 1 0 $count)
       (collect $count $counts))
     (sum $counts $output)))

;; def colorfilter(objs: Objects, value: Integer) -> Objects: ;; """ filter objects by color """ ;; return frozenset((obj for obj in objs if next(iter(obj))[0] == value))

(= (colorfilter $objs $value $output)
   (match-and &self
     "filter objects by color"
     (length $objs $len)
     (match-all &self
       "iterate over objects"
       (range 0 $len 1 $i)
       (tuple-index $objs $i $obj)
       (tuple-index $obj 0 $first-element)
       (tuple-index $first-element 0 $first-value)
       (== $first-value $value)
       (collect $obj $filtered-objs)))
     (make-frozenset $filtered-objs $output)))

;; $objs is not empty and $first-value matches $value (became a separate statement)
(= (colorfilter $objs $value $output)
   (match-and &self
     "filter objects by color"
     (length $objs $len)
     (match-all &self
       "iterate over objects"
       (range 0 $len 1 $i)
       (tuple-index $objs $i $obj)
       (tuple-index $obj 0 $first-element)
       (tuple-index $first-element 0 $first-value)
       (== $first-value $value)
       (collect $obj $filtered-objs)))
     (make-frozenset $filtered-objs $output)))

;; def sizefilter(container: Container, n: Integer) -> FrozenSet: ;; """ filter items by size """ ;; return frozenset((item for item in container if len(item) == n))

;; Extracted length of item into a separate statement
(= (sizefilter $container $n $output)
   (match-and &self
     "filter items by size"
     (length $container $len)
     (match-all &self
       "iterate over items"
       (range 0 $len 1 $i)
       (tuple-index $container $i $item)
       (length $item $item-len)
       (== $item-len $n)
       (collect $item $filtered-items)))
     (make-frozenset $filtered-items $output)))

;; def asindices(grid: Grid) -> Indices: ;; """ indices of all grid cells """ ;; return frozenset(((i, j) for i in range(len(grid)) for j in range(len(grid[0]))))

;; Extracted $first-row and $len-row into separate statements
(= (asindices $grid $output)
   (match-and &self
     "indices of all grid cells"
     (length $grid $len)
     (tuple-index $grid 0 $first-row)
     (length $first-row $len-row)
     (match-all &self
       "iterate over rows"
       (range 0 $len 1 $i)
       (match-all &self
         "iterate over columns"
         (range 0 $len-row 1 $j)
         (make-tuple ($i $j) $index)
         (collect $index $indices)))
     (make-frozenset $indices $output)))

;; def ofcolor(grid: Grid, value: Integer) -> Indices: ;; """ indices of all grid cells with value """ ;; return frozenset(((i, j) for i, r in enumerate(grid) for j, v in enumerate(r) if v == value))

;; Extracted length of row into a separate statement
(= (ofcolor $grid $value $output)
   (match-and &self
     "indices of all grid cells with value"
     (length $grid $len)
     (match-all &self
       "iterate over rows"
       (range 0 $len 1 $i)
       (tuple-index $grid $i $r)
       (length $r $len-r) ;; Extracted length of row into a separate statement
       (match-all &self
         "iterate over values in row"
         (range 0 $len-r 1 $j)
         (tuple-index $r $j $v)
         (== $v $value)
         (make-tuple ($i $j) $index)
         (collect $index $indices)))
     (make-frozenset $indices $output)))

;; def ulcorner(patch: Patch) -> IntegerTuple: ;; """ index of upper left corner """ ;; return tuple(map(min, zip(*toindices(patch))))

;; Extracted intermediate expressions into separate statements
(= (ulcorner $patch $output)
   (match-and &self
     "index of upper left corner"
     (toindices $patch $indices)
     (zip $indices $zipped)
     (map $zipped min-helper $mins)
     (make-tuple $mins $output)))

;; No changes needed for min-helper as it is already simple and doesn't have nested expressions
(= (min-helper $values $out)
   (match-and &self
     "find minimum value"
     (min $values $out)))

;; def urcorner(patch: Patch) -> IntegerTuple: ;; """ index of upper right corner """ ;; return tuple(map(lambda ix: {0: min, 1: max}ix[0], enumerate(zip(*toindices(patch)))))

(= (urcorner $patch $output)
   (match-and &self
     "index of upper right corner"
     (toindices $patch $indices)
     (zip $indices $zipped)
     (enumerate $zipped $enumerated)
     (map $enumerated urcorner-helper $output)))

(= (urcorner-helper $ix $out)
   (match-and &self
     "helper for upper right corner"
     (tuple-index $ix 0 $ix0)
     (tuple-index $ix 1 $ix1)
     (make-tuple (0 min) (1 max) $func-map)
     (tuple-index $func-map $ix0 $func)
     ;; Extracted function application into a separate statement
     ($func $ix1 $func-result)
     ;; Use the extracted variable
     (var $out $func-result)))

;; def llcorner(patch: Patch) -> IntegerTuple: ;; """ index of lower left corner """ ;; return tuple(map(lambda ix: {0: max, 1: min}ix[0], enumerate(zip(*toindices(patch)))))

;; Extracted intermediate expressions into separate statements
(= (llcorner $patch $output)
   (match-and &self
     "index of lower left corner"
     (toindices $patch $indices)
     (transpose $indices $transposed)
     (enumerate $transposed $enumerated)
     (map $enumerated llcorner-helper $mapped)
     (make-tuple $mapped $output)))

;; $index is 0 (became a separate statement)
(= (llcorner-helper $ix $out)
   (match-and &self
     "helper for llcorner"
     (tuple-index $ix 0 $index)
     (tuple-index $ix 1 $values)
     (match-and &self
       "choose function based on index"
       (== $index 0)
       (max $values $out))))

;; $index is 1 (became a separate statement)
(= (llcorner-helper $ix $out)
   (match-and &self
     "helper for llcorner"
     (tuple-index $ix 0 $index)
     (tuple-index $ix 1 $values)
     (match-and &self
       "choose function based on index"
       (== $index 1)
       (min $values $out))))

;; def lrcorner(patch: Patch) -> IntegerTuple: ;; """ index of lower right corner """ ;; return tuple(map(max, zip(*toindices(patch))))

(= (lrcorner $patch $output)
   (match-and &self
     "index of lower right corner"
     (toindices $patch $indices)
     (transpose $indices $transposed)
     (length $transposed $len)
     (match-all &self
       "iterate over transposed indices"
       (range 0 $len 1 $i)
       (tuple-index $transposed $i $column)
       (max $column $max-value)
       (collect $max-value $max-values))
     (make-tuple $max-values $output))) ;; No changes needed for this part, as $output is only assigned once

;; def crop(grid: Grid, start: IntegerTuple, dims: IntegerTuple) -> Grid: ;; """ subgrid specified by start and dimension """ ;; return tuple((r[start[1]:start[1] + dims[1]] for r in grid[start[0]:start[0] + dims[0]]))

;; Extracted $end-row calculation into a separate statement
;; Extracted $end-col calculation into a separate statement
;; Extracted $grid-len-1 calculation into a separate statement
(= (crop $grid $start $dims $output)
   (match-and &self
     "subgrid specified by start and dimension"
     (tuple-index $start 0 $start-row)
     (tuple-index $start 1 $start-col)
     (tuple-index $dims 0 $dim-rows)
     (tuple-index $dims 1 $dim-cols)
     (+ $start-row $dim-rows $end-row)
     (+ $start-col $dim-cols $end-col)
     (length $grid $grid-len)
     (- $grid-len 1 $grid-len-1)
     (match-all &self
       "iterate over rows"
       (range $start-row $end-row 1 $i)
       (tuple-index $grid $i $r)
       (length $r $row-len)
       (- $row-len 1 $row-len-1)
       (match-all &self
         "slice each row"
         (range $start-col $end-col 1 $j)
         (tuple-index $r $j $v)
         (collect $v $new-row))
       (make-tuple $new-row $new-r)
       (collect $new-r $new-grid))
     (make-tuple $new-grid $output)))

;; def toindices(patch: Patch) -> Indices: ;; """ indices of object cells """ ;; if len(patch) == 0: ;; return frozenset() ;; if isinstance(next(iter(patch))[1], tuple): ;; return frozenset((index for value, index in patch)) ;; return patch

;; $patch is empty (no changes needed)
(= (toindices $patch $output)
   (match-and &self
     "indices of object cells"
     (length $patch 0)
     (make-frozenset () $output)))

;; $patch is not empty and $first-value is a tuple (extracted iter and next into separate statements)
(= (toindices $patch $output)
   (match-and &self
     "indices of object cells"
     (not (length $patch 0))
     (iter $patch $patch-iter) ;; Extracted iter into a separate statement
     (next $patch-iter $first) ;; Extracted next into a separate statement
     (tuple-index $first 1 $first-value)
     (is-tuple $first-value)
     (length $patch $len)
     (match-all &self
       "iterate over patch"
       (range 0 $len 1 $i)
       (tuple-index $patch $i $pair)
       (tuple-index $pair 1 $index)
       (collect $index $indices))
     (make-frozenset $indices $output)))

;; $patch is not empty and $first-value is not a tuple (extracted iter and next into separate statements)
(= (toindices $patch $output)
   (match-and &self
     "indices of object cells"
     (not (length $patch 0))
     (iter $patch $patch-iter) ;; Extracted iter into a separate statement
     (next $patch-iter $first) ;; Extracted next into a separate statement
     (tuple-index $first 1 $first-value)
     (not (is-tuple $first-value))
     (var $output $patch)))

;; def recolor(value: Integer, patch: Patch) -> Object: ;; """ recolor patch """ ;; return frozenset(((value, index) for index in toindices(patch)))

;; Extracted tuple-index into a separate statement
(= (recolor $value $patch $output)
   (match-and &self
     "recolor patch"
     (toindices $patch $indices)
     (length $indices $len)
     (match-all &self
       "iterate over indices"
       (range 0 $len 1 $i)
       (tuple-index $indices $i $index)
       (make-tuple ($value $index) $pair)
       (collect $pair $pairs))
     (make-frozenset $pairs $output)))

;; def shift(patch: Patch, directions: IntegerTuple) -> Patch: ;; """ shift patch """ ;; di, dj = directions ;; if isinstance(next(iter(patch))[1], tuple): ;; return frozenset(((value, (i + di, j + dj)) for value, (i, j) in patch)) ;; return frozenset(((i + di, j + dj) for i, j in patch))

;; First case: when $first-value is a tuple
(= (shift $patch $directions $output)
   (match-and &self
     "shift patch"
     (tuple-index $directions 0 $di)
     (tuple-index $directions 1 $dj)
     (first $patch $first-element)
     (tuple-index $first-element 1 $first-value)
     (is-tuple $first-value)
     (length $patch $len)
     (match-all &self
       "iterate over patch elements"
       (range 0 $len 1 $i)
       (tuple-index $patch $i $element)
       (tuple-index $element 0 $value)
       (tuple-index $element 1 $coords)
       (tuple-index $coords 0 $i-coord)
       (tuple-index $coords 1 $j-coord)
       (+ $i-coord $di $new-i)
       (+ $j-coord $dj $new-j)
       (make-tuple ($new-i $new-j) $new-coords) ;; Extracted new coordinates into a separate statement
       (make-tuple ($value $new-coords) $new-element) ;; Use the extracted variable
       (collect $new-element $new-elements))
     (make-frozenset $new-elements $output)))

;; Second case: when $first-value is not a tuple
(= (shift $patch $directions $output)
   (match-and &self
     "shift patch"
     (tuple-index $directions 0 $di)
     (tuple-index $directions 1 $dj)
     (first $patch $first-element)
     (tuple-index $first-element 1 $first-value)
     (not (is-tuple $first-value))
     (length $patch $len)
     (match-all &self
       "iterate over patch elements"
       (range 0 $len 1 $i)
       (tuple-index $patch $i $element)
       (tuple-index $element 0 $i-coord)
       (tuple-index $element 1 $j-coord)
       (+ $i-coord $di $new-i)
       (+ $j-coord $dj $new-j)
       (make-tuple ($new-i $new-j) $new-element)
       (collect $new-element $new-elements))
     (make-frozenset $new-elements $output)))

;; def normalize(patch: Patch) -> Patch: ;; """ moves upper left corner to origin """ ;; return shift(patch, (-uppermost(patch), -leftmost(patch)))

;; Extracted neg-uppermost and neg-leftmost into separate statements
(= (normalize $patch $output)
   (match-and &self
     "moves upper left corner to origin"
     (uppermost $patch $uppermost)
     (leftmost $patch $leftmost)
     (- 0 $uppermost $neg-uppermost)
     (- 0 $leftmost $neg-leftmost)
     (make-tuple ($neg-uppermost $neg-leftmost) $shift-amount) ;; Use the extracted variables
     (shift $patch $shift-amount $output)))

;; def dneighbors(loc: IntegerTuple) -> Indices: ;; """ directly adjacent indices """ ;; return frozenset({(loc[0] - 1, loc[1]), (loc[0] + 1, loc[1]), (loc[0], loc[1] - 1), (loc[0], loc[1] + 1)})

;; Extracted intermediate expressions into separate statements
(= (dneighbors $loc $indices)
   (match-and &self
     "directly adjacent indices"
     (tuple-index $loc 0 $x)
     (tuple-index $loc 1 $y)
     (- $x 1 $x1)
     (+ $x 1 $x2)
     (- $y 1 $y1)
     (+ $y 1 $y2)
     (make-tuple ($x1 $y) $t1)
     (make-tuple ($x2 $y) $t2)
     (make-tuple ($x $y1) $t3)
     (make-tuple ($x $y2) $t4)
     (make-tuple ($t1 $t2 $t3 $t4) $temp-tuple) ;; Extracted tuple of tuples into a separate statement
     (make-frozenset $temp-tuple $indices))) ;; Use the extracted variable

;; def ineighbors(loc: IntegerTuple) -> Indices: ;; """ diagonally adjacent indices """ ;; return frozenset({(loc[0] - 1, loc[1] - 1), (loc[0] - 1, loc[1] + 1), (loc[0] + 1, loc[1] - 1), (loc[0] + 1, loc[1] + 1)})

;; Extracted intermediate expressions into separate statements using temporary variables
(= (ineighbors $loc $indices)
   (match-and &self
     "diagonally adjacent indices"
     (tuple-index $loc 0 $x)
     (tuple-index $loc 1 $y)
     (- $x 1 $x1)
     (- $y 1 $y1)
     (+ $y 1 $y2)
     (+ $x 1 $x2)
     (make-tuple ($x1 $y1) $t1)
     (make-tuple ($x1 $y2) $t2)
     (make-tuple ($x2 $y1) $t3)
     (make-tuple ($x2 $y2) $t4)
     (make-tuple ($t1 $t2 $t3 $t4) $all-tuples) ;; Extracted all tuples into a separate statement
     (make-frozenset $all-tuples $indices))) ;; Use the extracted variable

;; def neighbors(loc: IntegerTuple) -> Indices: ;; """ adjacent indices """ ;; return dneighbors(loc) | ineighbors(loc)

;; Extracted intermediate expressions into separate statements using temporary variables
(= (neighbors $loc $output)
   (match-and &self
     "adjacent indices"
     (dneighbors $loc $dneighbors-output)
     (ineighbors $loc $ineighbors-output)
     (union $dneighbors-output $ineighbors-output $union-output) ;; Extracted union into a separate statement
     (var $output $union-output))) ;; Use the extracted variable

;; def objects(grid: Grid, univalued: Boolean, diagonal: Boolean, without_bg: Boolean) -> Objects: ;; """ objects occurring on the grid """ ;; bg = mostcolor(grid) if without_bg else None ;; objs = set() ;; occupied = set() ;; h, w = (len(grid), len(grid[0])) ;; unvisited = asindices(grid) ;; diagfun = neighbors if diagonal else dneighbors ;; for loc in unvisited: ;; if loc in occupied: ;; continue ;; val = grid[loc[0]][loc[1]] ;; if val == bg: ;; continue ;; obj = {(val, loc)} ;; cands = {loc} ;; while len(cands) > 0: ;; neighborhood = set() ;; for cand in cands: ;; v = grid[cand[0]][cand[1]] ;; if val == v if univalued else v != bg: ;; obj.add((v, cand)) ;; occupied.add(cand) ;; neighborhood |= {(i, j) for i, j in diagfun(cand) if 0 <= i < h and 0 <= j < w} ;; cands = neighborhood - occupied ;; objs.add(frozenset(obj)) ;; return frozenset(objs)

;; Extracted the result of the if statement into a separate statement
(= (objects $grid $univalued $diagonal $without-bg $output)
   (match-and &self
     "objects occurring on the grid"
     (if $without-bg
         (mostcolor $grid $bg)
         (var $bg nil))
     (make-set () $objs)
     (make-set () $occupied)
     (length $grid $h)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     (asindices $grid $unvisited)
     (if $diagonal
         (var $diagfun neighbors)
         (var $diagfun dneighbors))
     (match-all &self
       "iterate over unvisited locations"
       (length $unvisited $unvisited-len)
       (range 0 $unvisited-len 1 $i)
       (tuple-index $unvisited $i $loc)
       (not (contains $occupied $loc))
       (tuple-index $loc 0 $loc-x)
       (tuple-index $loc 1 $loc-y)
       (tuple-index $grid $loc-x $row)
       (tuple-index $row $loc-y $val)
       (not (== $val $bg))
       (make-set ((make-tuple ($val $loc))) $obj)
       (make-set ($loc) $cands)
       (process-candidates $grid $h $w $val $univalued $bg $diagfun $cands $obj $occupied $new-obj $new-occupied)
       (add-to-set $objs $new-obj $new-objs))
     (make-frozenset $new-objs $output)))

;; Extracted the result of the if statement into a separate statement
;; Extracted neighborhood calculation into a separate statement
(= (process-candidates $grid $h $w $val $univalued $bg $diagfun $cands $obj $occupied $new-obj $new-occupied)
   (match-and &self
     "process candidates"
     (length $cands $cands-len)
     (not (== $cands-len 0))
     (make-set () $neighborhood)
     (match-all &self
       "iterate over candidates"
       (range 0 $cands-len 1 $j)
       (tuple-index $cands $j $cand)
       (tuple-index $cand 0 $cand-x)
       (tuple-index $cand 1 $cand-y)
       (tuple-index $grid $cand-x $cand-row)
       (tuple-index $cand-row $cand-y $v)
       (if $univalued
           (== $val $v)
           (not (== $v $bg)))
       (add-to-set $obj (make-tuple ($v $cand)) $new-obj)
       (add-to-set $occupied $cand $new-occupied)
       (diagfun $cand $neighbors)
       (length $neighbors $neighbors-len)
       (match-all &self
         "iterate over neighbors"
         (range 0 $neighbors-len 1 $k)
         (tuple-index $neighbors $k $neighbor)
         (tuple-index $neighbor 0 $i)
         (tuple-index $neighbor 1 $j)
         (>= $i 0)
         (< $i $h)
         (>= $j 0)
         (< $j $w)
         (add-to-set $neighborhood $neighbor $new-neighborhood)))
     (set-difference $new-neighborhood $new-occupied $new-cands)
     (process-candidates $grid $h $w $val $univalued $bg $diagfun $new-cands $new-obj $new-occupied $final-obj $final-occupied)
     (var $new-obj $final-obj)
     (var $new-occupied $final-occupied)))

;; Base case for process-candidates, no changes needed
(= (process-candidates $grid $h $w $val $univalued $bg $diagfun $cands $obj $occupied $obj $occupied)
   (match-and &self
     "process candidates base case"
     (length $cands $cands-len)
     (== $cands-len 0)))

;; def partition(grid: Grid) -> Objects: ;; """ each cell with the same value part of the same object """ ;; return frozenset((frozenset(((v, (i, j)) for i, r in enumerate(grid) for j, v in enumerate(r) if v == value)) for value in palette(grid)))

(= (partition $grid $output)
   (match-and &self
     "each cell with the same value part of the same object"
     (palette $grid $palette)
     (length $palette $palette-len)
     (match-all &self
       "iterate over palette values"
       (range 0 $palette-len 1 $k)
       (tuple-index $palette $k $value)
       (length $grid $len)
       (match-all &self
         "iterate over rows"
         (range 0 $len 1 $i)
         (tuple-index $grid $i $r)
         (length $r $len-r)
         (match-all &self
           "iterate over values in row"
           (range 0 $len-r 1 $j)
           (tuple-index $r $j $v)
           (== $v $value)
           (make-tuple ($i $j) $coords) ;; Extracted coordinates into a separate statement
           (make-tuple ($v $coords) $cell) ;; Use the extracted variable
           (collect $cell $cells)))
       (make-frozenset $cells $object)
       (collect $object $objects)))
     (make-frozenset $objects $output)))

;; def fgpartition(grid: Grid) -> Objects: ;; """ each cell with the same value part of the same object without background """ ;; return frozenset((frozenset(((v, (i, j)) for i, r in enumerate(grid) for j, v in enumerate(r) if v == value)) for value in palette(grid) - {mostcolor(grid)}))

(= (fgpartition $grid $output)
   (match-and &self
     "each cell with the same value part of the same object without background"
     (palette $grid $palette)
     (mostcolor $grid $most-color)
     (set-remove $palette $most-color $filtered-palette)
     (length $filtered-palette $len)
     (match-all &self
       "iterate over unique values"
       (range 0 $len 1 $k)
       (tuple-index $filtered-palette $k $value)
       (length $grid $grid-len)
       (match-all &self
         "iterate over rows"
         (range 0 $grid-len 1 $i)
         (tuple-index $grid $i $r)
         (length $r $row-len)
         (match-all &self
           "iterate over values in row"
           (range 0 $row-len 1 $j)
           (tuple-index $r $j $v)
           (== $v $value)
           (make-tuple ($i $j) $coords) ;; Extracted coordinates into a separate statement
           (make-tuple ($v $coords) $cell) ;; Use the extracted variable
           (collect $cell $cells)))
       (make-frozenset $cells $object)
       (collect $object $objects))
     (make-frozenset $objects $output)))

;; def uppermost(patch: Patch) -> Integer: ;; """ row index of uppermost occupied cell """ ;; return min((i for i, j in toindices(patch)))

(= (uppermost $patch $output)
   (match-and &self
     "row index of uppermost occupied cell"
     (toindices $patch $indices)
     (length $indices $len)
     (match-all &self
       "iterate over indices"
       (range 0 $len 1 $i)
       (tuple-index $indices $i $index)
       (tuple-index $index 0 $row)
       (collect $row $rows))
     (min $rows $min-row) ;; Extracted min into a separate statement
     (var $output $min-row))) ;; Use the extracted variable

;; def lowermost(patch: Patch) -> Integer: ;; """ row index of lowermost occupied cell """ ;; return max((i for i, j in toindices(patch)))

;; Extracted length of indices into a separate statement
(= (lowermost $patch $output)
   (match-and &self
     "row index of lowermost occupied cell"
     (toindices $patch $indices)
     (length $indices $len)
     (match-all &self
       "iterate over indices"
       (range 0 $len 1 $i)
       (tuple-index $indices $i $pair)
       (tuple-index $pair 0 $row-index)
       (collect $row-index $row-indices))
     (max $row-indices $output)))

;; def leftmost(patch: Patch) -> Integer: ;; """ column index of leftmost occupied cell """ ;; return min((j for i, j in toindices(patch)))

;; Extracted tuple-index into a separate statement
(= (leftmost $patch $output)
   (match-and &self
     "column index of leftmost occupied cell"
     (toindices $patch $indices)
     (length $indices $len)
     (match-all &self
       "iterate over indices"
       (range 0 $len 1 $i)
       (tuple-index $indices $i $pair)
       (tuple-index $pair 1 $j) ;; Extracted column index into a separate statement
       (collect $j $columns))
     (min $columns $output)))

;; def rightmost(patch: Patch) -> Integer: ;; """ column index of rightmost occupied cell """ ;; return max((j for i, j in toindices(patch)))

;; Extracted tuple-index into a separate statement
(= (rightmost $patch $output)
   (match-and &self
     "column index of rightmost occupied cell"
     (toindices $patch $indices)
     (length $indices $len)
     (match-all &self
       "iterate over indices"
       (range 0 $len 1 $i)
       (tuple-index $indices $i $index)
       (tuple-index $index 1 $j)
       (collect $j $js))
     (max $js $output))) ;; No change needed here as $output is assigned only once

;; def square(piece: Piece) -> Boolean: ;; """ whether the piece forms a square """ ;; return len(piece) == len(piece[0]) if isinstance(piece, tuple) else height(piece) * width(piece) == len(piece) and height(piece) == width(piece)

;; $piece is a tuple (became a separate statement)
(= (square $piece $output)
   (match-and &self
     "whether the piece forms a square"
     (is-tuple $piece)
     (length $piece $len)
     (tuple-index $piece 0 $first-row)
     (length $first-row $first-row-len)
     (== $len $first-row-len $output)))

;; $piece is not a tuple (became a separate statement)
(= (square $piece $output)
   (match-and &self
     "whether the piece forms a square"
     (not (is-tuple $piece))
     (height $piece $height)
     (width $piece $width)
     (* $height $width $area)
     (length $piece $len)
     (== $area $len)
     (== $height $width $output)))

;; def vline(patch: Patch) -> Boolean: ;; """ whether the piece forms a vertical line """ ;; return height(patch) == len(patch) and width(patch) == 1

;; $patch forms a vertical line (became a separate statement)
(= (vline $patch $output)
   (match-and &self
     "whether the piece forms a vertical line"
     (height $patch $height)
     (length $patch $len)
     (== $height $len)
     (width $patch 1)
     (var $output true)))

;; def hline(patch: Patch) -> Boolean: ;; """ whether the piece forms a horizontal line """ ;; return width(patch) == len(patch) and height(patch) == 1

;; $patch forms a horizontal line with width equal to length and height 1 (became a separate statement)
(= (hline $patch $output)
   (match-and &self
     "whether the piece forms a horizontal line"
     (width $patch $w)
     (length $patch $len)
     (== $w $len)
     (height $patch 1)
     (var $output true)))

;; $patch does not form a horizontal line because width is not equal to length (became a separate statement)
(= (hline $patch $output)
   (match-and &self
     "whether the piece forms a horizontal line"
     (width $patch $w)
     (length $patch $len)
     (not (== $w $len))
     (var $output false)))

;; $patch does not form a horizontal line because height is not 1 (became a separate statement)
(= (hline $patch $output)
   (match-and &self
     "whether the piece forms a horizontal line"
     (width $patch $w)
     (length $patch $len)
     (== $w $len)
     (height $patch $h)
     (not (== $h 1))
     (var $output false)))

;; def hmatching(a: Patch, b: Patch) -> Boolean: ;; """ whether there exists a row for which both patches have cells """ ;; return len(set((i for i, j in toindices(a))) & set((i for i, j in toindices(b)))) > 0

(= (hmatching $a $b $output)
   (match-and &self
     "whether there exists a row for which both patches have cells"
     (toindices $a $indices-a)
     (toindices $b $indices-b)
     (length $indices-a $len-a)
     (length $indices-b $len-b)
     (match-all &self
       "collect row indices from patch a"
       (range 0 $len-a 1 $i)
       (tuple-index $indices-a $i $index-a)
       (tuple-index $index-a 0 $row-a)
       (collect $row-a $rows-a))
     (match-all &self
       "collect row indices from patch b"
       (range 0 $len-b 1 $j)
       (tuple-index $indices-b $j $index-b)
       (tuple-index $index-b 0 $row-b)
       (collect $row-b $rows-b))
     (make-set $rows-a $set-a)
     (make-set $rows-b $set-b)
     (intersection $set-a $set-b $common-rows)
     (length $common-rows $common-len)
     (> $common-len 0 $has-common-rows) ;; Extracted comparison result into a separate variable
     (var $output $has-common-rows))) ;; Use the extracted variable

;; def vmatching(a: Patch, b: Patch) -> Boolean: ;; """ whether there exists a column for which both patches have cells """ ;; return len(set((j for i, j in toindices(a))) & set((j for i, j in toindices(b)))) > 0

(= (vmatching $a $b $output)
   (match-and &self
     "whether there exists a column for which both patches have cells"
     (toindices $a $indices-a)
     (toindices $b $indices-b)
     (length $indices-a $len-a)
     (length $indices-b $len-b)
     (match-all &self
       "collect columns from indices of a"
       (range 0 $len-a 1 $i)
       (tuple-index $indices-a $i $index-a)
       (tuple-index $index-a 1 $j-a)
       (collect $j-a $columns-a))
     (match-all &self
       "collect columns from indices of b"
       (range 0 $len-b 1 $j)
       (tuple-index $indices-b $j $index-b)
       (tuple-index $index-b 1 $j-b)
       (collect $j-b $columns-b))
     (make-set $columns-a $set-a)
     (make-set $columns-b $set-b)
     (intersection $set-a $set-b $common-columns)
     (length $common-columns $common-len)
     ;; Extracted comparison into a separate statement
     (> $common-len 0 $is-common)
     (var $output $is-common))) ;; Use the extracted variable

;; def manhattan(a: Patch, b: Patch) -> Integer: ;; """ closest manhattan distance between two patches """ ;; return min((abs(ai - bi) + abs(aj - bj) for ai, aj in toindices(a) for bi, bj in toindices(b)))

(= (manhattan $a $b $output)
   (match-and &self
     "closest manhattan distance between two patches"
     (toindices $a $indices-a)
     (toindices $b $indices-b)
     (length $indices-a $len-a)
     (length $indices-b $len-b)
     (match-all &self
       "iterate over indices of a"
       (range 0 $len-a 1 $i)
       (tuple-index $indices-a $i $pair-a)
       (tuple-index $pair-a 0 $ai)
       (tuple-index $pair-a 1 $aj)
       (match-all &self
         "iterate over indices of b"
         (range 0 $len-b 1 $j)
         (tuple-index $indices-b $j $pair-b)
         (tuple-index $pair-b 0 $bi)
         (tuple-index $pair-b 1 $bj)
         (- $ai $bi $diff-i)
         (abs $diff-i $abs-i)
         (- $aj $bj $diff-j)
         (abs $diff-j $abs-j)
         (+ $abs-i $abs-j $manhattan-distance)
         (collect $manhattan-distance $distances)))
     (min $distances $output)))

;; Extracted tuple-index for $indices-b into separate statements
;; Extracted difference and absolute value calculations into separate statements

;; def adjacent(a: Patch, b: Patch) -> Boolean: ;; """ whether two patches are adjacent """ ;; return manhattan(a, b) == 1

;; Extracted manhattan distance calculation into a separate statement
(= (adjacent $a $b $output)
   (match-and &self
     "whether two patches are adjacent"
     (manhattan $a $b $distance)
     (== $distance 1 $is-adjacent) ;; Extracted the comparison into a separate statement
     (var $output $is-adjacent))) ;; Use the extracted variable

;; def bordering(patch: Patch, grid: Grid) -> Boolean: ;; """ whether a patch is adjacent to a grid border """ ;; return uppermost(patch) == 0 or leftmost(patch) == 0 or lowermost(patch) == len(grid) - 1 or (rightmost(patch) == len(grid[0]) - 1)

;; $patch is uppermost (became a separate statement)
(= (bordering $patch $grid $output)
   (match-and &self
     "whether a patch is adjacent to a grid border"
     (uppermost $patch 0)
     (var $output true)))

;; $patch is leftmost (became a separate statement)
(= (bordering $patch $grid $output)
   (match-and &self
     "whether a patch is adjacent to a grid border"
     (leftmost $patch 0)
     (var $output true)))

;; $patch is lowermost (became a separate statement)
(= (bordering $patch $grid $output)
   (match-and &self
     "whether a patch is adjacent to a grid border"
     (lowermost $patch $lowermost)
     (length $grid $grid-len)
     (- $grid-len 1 $lowermost-minus-one) ;; Extracted subtraction into a separate statement
     (== $lowermost $lowermost-minus-one) ;; Use the extracted variable
     (var $output true)))

;; $patch is rightmost (became a separate statement)
(= (bordering $patch $grid $output)
   (match-and &self
     "whether a patch is adjacent to a grid border"
     (rightmost $patch $rightmost)
     (tuple-index $grid 0 $first-row)
     (length $first-row $first-row-len)
     (- $first-row-len 1 $rightmost-minus-one) ;; Extracted subtraction into a separate statement
     (== $rightmost $rightmost-minus-one) ;; Use the extracted variable
     (var $output true)))

;; $patch is not adjacent to any border (became a separate statement)
(= (bordering $patch $grid $output)
   (match-and &self
     "whether a patch is adjacent to a grid border"
     (var $output false)))

;; def centerofmass(patch: Patch) -> IntegerTuple: ;; """ center of mass """ ;; return tuple(map(lambda x: sum(x) // len(patch), zip(*toindices(patch))))

;; Extracted intermediate expressions into separate statements
(= (centerofmass $patch $output)
   (match-and &self
     "center of mass"
     (toindices $patch $indices)
     (zip $indices $zipped)
     (map $zipped sum-helper $sums)
     (length $patch $len)
     (map $sums (center-helper $len) $output))) ;; Passed $len to center-helper

;; Extracted sum operation into a separate statement
(= (sum-helper $x $out)
   (match-and &self
     "sum each item"
     (sum $x $sum) ;; Extracted sum into a separate statement
     (var $out $sum))) ;; Assigned the extracted sum to $out

;; Extracted division operation into a separate statement
(= (center-helper $len $sum $out) ;; Added $len as a parameter
   (match-and &self
     "calculate center"
     (// $sum $len $center) ;; Extracted division into a separate statement
     (var $out $center))) ;; Assigned the extracted center to $out

;; def palette(element: Element) -> IntegerSet: ;; """ colors occurring in object or grid """ ;; if isinstance(element, tuple): ;; return frozenset({v for r in element for v in r}) ;; return frozenset({v for v, _ in element})

;; $element is a tuple (became a separate statement)
(= (palette $element $output)
   (match-and &self
     "colors occurring in object or grid"
     (is-tuple $element)
     (length $element $len)
     (match-all &self
       "iterate over rows"
       (range 0 $len 1 $i)
       (tuple-index $element $i $r)
       (length $r $len-r)
       (match-all &self
         "iterate over values in row"
         (range 0 $len-r 1 $j)
         (tuple-index $r $j $v)
         (collect $v $values))))
     (make-frozenset $values $output)))

;; $element is not a tuple (became a separate statement)
(= (palette $element $output)
   (match-and &self
     "colors occurring in object or grid"
     (not (is-tuple $element))
     (length $element $len)
     (match-all &self
       "iterate over element pairs"
       (range 0 $len 1 $i)
       (tuple-index $element $i $pair)
       (tuple-index $pair 0 $v)
       (collect $v $values)))
     (make-frozenset $values $output)))

;; def numcolors(element: Element) -> IntegerSet: ;; """ number of colors occurring in object or grid """ ;; return len(palette(element))

;; Extracted palette length into a separate statement
(= (numcolors $element $output)
   (match-and &self
     "number of colors occurring in object or grid"
     (palette $element $palette)
     (length $palette $palette-length) ;; Extracted length into a separate variable
     (var $output $palette-length))) ;; Use the extracted variable

;; def color(obj: Object) -> Integer: ;; """ color of object """ ;; return next(iter(obj))[0]

;; Extracted the first element into a separate statement
(= (color $obj $output)
   (match-and &self
     "color of object"
     (next $obj $iter)
     (iter $iter $first)
     (tuple-index $first 0 $first-element) ;; Extracted first element into a separate statement
     (var $output $first-element))) ;; Use the extracted variable

;; def toobject(patch: Patch, grid: Grid) -> Object: ;; """ object from patch and grid """ ;; h, w = (len(grid), len(grid[0])) ;; return frozenset(((grid[i][j], (i, j)) for i, j in toindices(patch) if 0 <= i < h and 0 <= j < w))

(= (toobject $patch $grid $output)
   (match-and &self
     "object from patch and grid"
     (length $grid $h)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     (toindices $patch $indices)
     (length $indices $len)
     (match-all &self
       "iterate over indices"
       (range 0 $len 1 $k)
       (tuple-index $indices $k $index)
       (tuple-index $index 0 $i)
       (tuple-index $index 1 $j)
       (>= $i 0)
       (< $i $h)
       (>= $j 0)
       (< $j $w)
       (tuple-index $grid $i $row)
       (tuple-index $row $j $value)
       (make-tuple ($value $index) $pair)
       (collect $pair $pairs))
     (make-frozenset $pairs $output)))

;; $i and $j are within grid bounds (became a separate statement)
(= (toobject $patch $grid $output)
   (match-and &self
     "object from patch and grid"
     (length $grid $h)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     (toindices $patch $indices)
     (length $indices $len)
     (match-all &self
       "iterate over indices"
       (range 0 $len 1 $k)
       (tuple-index $indices $k $index)
       (tuple-index $index 0 $i)
       (tuple-index $index 1 $j)
       (>= $i 0)
       (< $i $h)
       (>= $j 0)
       (< $j $w)
       (tuple-index $grid $i $row)
       (tuple-index $row $j $value)
       (make-tuple ($value $index) $pair)
       (collect $pair $pairs))
     (make-frozenset $pairs $output)))

;; def asobject(grid: Grid) -> Object: ;; """ conversion of grid to object """ ;; return frozenset(((v, (i, j)) for i, r in enumerate(grid) for j, v in enumerate(r)))

(= (asobject $grid $output)
   (match-and &self
     "conversion of grid to object"
     (length $grid $len)
     (match-all &self
       "iterate over rows"
       (range 0 $len 1 $i)
       (tuple-index $grid $i $r)
       (length $r $len-r)
       (match-all &self
         "iterate over values in row"
         (range 0 $len-r 1 $j)
         (tuple-index $r $j $v)
         (make-tuple ($i $j) $coords) ;; Extracted coordinates into a separate statement
         (make-tuple ($v $coords) $pair) ;; Use the extracted variable
         (collect $pair $pairs)))
     (make-frozenset $pairs $output)))

;; def rot90(grid: Grid) -> Grid: ;; """ quarter clockwise rotation """ ;; return tuple((row for row in zip(*grid[::-1])))

(= (rot90 $grid $output)
   (match-and &self
     "quarter clockwise rotation"
     (reverse $grid $reversed-grid)
     (transpose $reversed-grid $transposed-grid)
     (make-tuple $transposed-grid $output)))

(= (reverse $grid $reversed-grid)
   (match-and &self
     "reverse grid"
     (length $grid $len)
     (- $len 1 $len-1)
     (match-all &self
       "iterate over indices in reverse"
       (range $len-1 -1 -1 $i)
       (tuple-index $grid $i $row)
       (collect $row $reversed-grid))))

(= (transpose $grid $transposed-grid)
   (match-and &self
     "transpose grid"
     (length $grid $len)
     (tuple-index $grid 0 $first-row)
     (length $first-row $row-len)
     (match-all &self
       "iterate over columns"
       (range 0 $row-len 1 $j)
       (match-all &self
         "collect column values"
         (range 0 $len 1 $i)
         (tuple-index $grid $i $row)
         (tuple-index $row $j $value)
         (collect $value $column))
       (make-tuple $column $transposed-row)
       (collect $transposed-row $transposed-grid))))

;; $grid is reversed and transposed (became a separate statement)
(= (rot90 $grid $output)
   (match-and &self
     "quarter clockwise rotation"
     (reverse $grid $reversed-grid)
     (transpose $reversed-grid $transposed-grid)
     (make-tuple $transposed-grid $output)))

;; def rot180(grid: Grid) -> Grid: ;; """ half rotation """ ;; return tuple((tuple(row[::-1]) for row in grid[::-1]))

(= (rot180 $grid $output)
   (match-and &self
     "half rotation"
     (length $grid $len)
     (- $len 1 $len-1) ;; Extracted $len-1 into a separate statement
     (match-all &self
       "iterate over rows in reverse"
       (range 0 $len 1 $i)
       (- $len-1 $i $rev-i) ;; Use the extracted $len-1
       (tuple-index $grid $rev-i $row)
       (length $row $len-row)
       (- $len-row 1 $len-row-1) ;; Extracted $len-row-1 into a separate statement
       (match-all &self
         "reverse each row"
         (range 0 $len-row 1 $j)
         (- $len-row-1 $j $rev-j) ;; Use the extracted $len-row-1
         (tuple-index $row $rev-j $val)
         (collect $val $new-row))
       (make-tuple $new-row $new-tuple-row)
       (collect $new-tuple-row $new-grid)))
     (make-tuple $new-grid $output)))

;; def rot270(grid: Grid) -> Grid: ;; """ quarter anticlockwise rotation """ ;; return tuple((tuple(row[::-1]) for row in zip(*grid[::-1])))[::-1]

(= (rot270 $grid $output)
   (match-and &self
     "quarter anticlockwise rotation"
     (reverse $grid $reversed-grid)
     (transpose $reversed-grid $transposed-grid)
     (length $transposed-grid $len)
     (match-all &self
       "iterate over transposed rows"
       (range 0 $len 1 $i)
       (tuple-index $transposed-grid $i $row)
       (reverse $row $reversed-row)
       (collect $reversed-row $reversed-rows))
     (make-tuple $reversed-rows $reversed-tuple)
     (reverse $reversed-tuple $output))) ;; No changes needed here

(= (transpose $matrix $transposed)
   (match-and &self
     "transpose matrix"
     (length $matrix $rows)
     (tuple-index $matrix 0 $first-row)
     (length $first-row $cols)
     (match-all &self
       "iterate over columns"
       (range 0 $cols 1 $j)
       (match-all &self
         "collect column elements"
         (range 0 $rows 1 $i)
         (tuple-index $matrix $i $row)
         (tuple-index $row $j $element)
         (collect $element $column))
       (make-tuple $column $col-tuple)
       (collect $col-tuple $transposed)))) ;; No changes needed here

;; def hmirror(piece: Piece) -> Piece: ;; """ mirroring along horizontal """ ;; if isinstance(piece, tuple): ;; return piece[::-1] ;; d = ulcorner(piece)[0] + lrcorner(piece)[0] ;; if isinstance(next(iter(piece))[1], tuple): ;; return frozenset(((v, (d - i, j)) for v, (i, j) in piece)) ;; return frozenset(((d - i, j) for i, j in piece))

;; Extracted reverse operation into a separate statement
(= (hmirror $piece $output)
   (match-and &self
     "mirroring along horizontal"
     (is-tuple $piece)
     (reverse $piece $reversed-piece) ;; Extracted reverse operation
     (var $output $reversed-piece))) ;; Use the extracted variable

;; Extracted multiple operations into separate statements
(= (hmirror $piece $output)
   (match-and &self
     "mirroring along horizontal"
     (not (is-tuple $piece))
     (ulcorner $piece $ulcorner)
     (lrcorner $piece $lrcorner)
     (tuple-index $ulcorner 0 $ulcorner-x)
     (tuple-index $lrcorner 0 $lrcorner-x)
     (+ $ulcorner-x $lrcorner-x $d)
     (next-iter $piece $first-element)
     (tuple-index $first-element 1 $first-element-second)
     (is-tuple $first-element-second)
     (make-frozenset $piece mirror-helper $frozenset-output) ;; Extracted frozenset operation
     (var $output $frozenset-output))) ;; Use the extracted variable

;; Extracted make-tuple operation into a separate statement
(= (mirror-helper $pair $out)
   (match-and &self
     "mirror helper for tuple"
     (tuple-index $pair 0 $v)
     (tuple-index $pair 1 $coords)
     (tuple-index $coords 0 $i)
     (tuple-index $coords 1 $j)
     (- $d $i $new-i)
     (make-tuple ($new-i $j) $new-coords) ;; Extracted new coordinates into a separate statement
     (make-tuple ($v $new-coords) $out))) ;; Use the extracted variable

;; Extracted multiple operations into separate statements
(= (hmirror $piece $output)
   (match-and &self
     "mirroring along horizontal"
     (not (is-tuple $piece))
     (ulcorner $piece $ulcorner)
     (lrcorner $piece $lrcorner)
     (tuple-index $ulcorner 0 $ulcorner-x)
     (tuple-index $lrcorner 0 $lrcorner-x)
     (+ $ulcorner-x $lrcorner-x $d)
     (next-iter $piece $next-iter-piece) ;; Extracted next-iter operation
     (tuple-index $next-iter-piece 1 $next-iter-second) ;; Use the extracted variable
     (not (is-tuple $next-iter-second))
     (make-frozenset $piece mirror-helper-simple $frozenset-output) ;; Extracted frozenset operation
     (var $output $frozenset-output))) ;; Use the extracted variable

;; Extracted make-tuple operation into a separate statement
(= (mirror-helper-simple $coords $out)
   (match-and &self
     "mirror helper for simple"
     (tuple-index $coords 0 $i)
     (tuple-index $coords 1 $j)
     (- $d $i $new-i)
     (make-tuple ($new-i $j) $out))) ;; No change needed here

;; def vmirror(piece: Piece) -> Piece: ;; """ mirroring along vertical """ ;; if isinstance(piece, tuple): ;; return tuple((row[::-1] for row in piece)) ;; d = ulcorner(piece)[1] + lrcorner(piece)[1] ;; if isinstance(next(iter(piece))[1], tuple): ;; return frozenset(((v, (i, d - j)) for v, (i, j) in piece)) ;; return frozenset(((i, d - j) for i, j in piece))

;; Extracted reverse row into a separate statement
(= (vmirror $piece $output)
   (match-and &self
     "mirroring along vertical"
     (is-tuple $piece)
     (length $piece $len)
     (match-all &self
       "iterate over rows"
       (range 0 $len 1 $i)
       (tuple-index $piece $i $row)
       (reverse $row $reversed-row)
       (collect $reversed-row $reversed-piece))
     (make-tuple $reversed-piece $output)))

;; Extracted tuple-index into separate statements and broke up make-frozenset into separate statements
(= (vmirror $piece $output)
   (match-and &self
     "mirroring along vertical"
     (not (is-tuple $piece))
     (ulcorner $piece $ulcorner)
     (lrcorner $piece $lrcorner)
     (tuple-index $ulcorner 1 $ulcorner-y)
     (tuple-index $lrcorner 1 $lrcorner-y)
     (+ $ulcorner-y $lrcorner-y $d)
     (tuple-index (next (iter $piece)) 1 $first-value)
     (is-tuple $first-value)
     (make-frozenset $piece $d $mirrored-piece)
     (make-frozenset $mirrored-piece $output)))

;; Extracted new coordinates into a separate statement
(= (make-frozenset $piece $d $output)
   (match-all &self
     "iterate over piece"
     (iter $piece $iterator)
     (next $iterator $element)
     (tuple-index $element 0 $v)
     (tuple-index $element 1 $coords)
     (tuple-index $coords 0 $i)
     (tuple-index $coords 1 $j)
     (- $d $j $new-j)
     (make-tuple ($i $new-j) $new-coords) ;; Extracted new coordinates into a separate statement
     (make-tuple ($v $new-coords) $new-element) ;; Use the extracted variable
     (collect $new-element $new-elements))
   (make-frozenset $new-elements $output)))

;; Extracted new coordinates into a separate statement
(= (make-frozenset $piece $d $output)
   (match-all &self
     "iterate over piece"
     (iter $piece $iterator)
     (next $iterator $element)
     (tuple-index $element 0 $i)
     (tuple-index $element 1 $j)
     (- $d $j $new-j)
     (make-tuple ($i $new-j) $new-element)
     (collect $new-element $new-elements))
   (make-frozenset $new-elements $output)))

;; def dmirror(piece: Piece) -> Piece: ;; """ mirroring along diagonal """ ;; if isinstance(piece, tuple): ;; return tuple(zip(*piece)) ;; a, b = ulcorner(piece) ;; if isinstance(next(iter(piece))[1], tuple): ;; return frozenset(((v, (j - b + a, i - a + b)) for v, (i, j) in piece)) ;; return frozenset(((j - b + a, i - a + b) for i, j in piece))

;; Extracted zip into a separate statement
(= (dmirror $piece $output)
   (match-and &self
     "mirroring along diagonal"
     (is-tuple $piece)
     (zip $piece $zipped)
     (make-tuple $zipped $output)))

;; Extracted next iteration into a separate statement
;; Extracted new coordinates into a separate statement
(= (dmirror $piece $output)
   (match-and &self
     "mirroring along diagonal"
     (not (is-tuple $piece))
     (ulcorner $piece $a $b)
     (next (iter $piece) $first)
     (tuple-index $first 1 $first-1)
     (is-tuple $first-1)
     (length $piece $len)
     (match-all &self
       "iterate over elements"
       (range 0 $len 1 $i)
       (tuple-index $piece $i $element)
       (tuple-index $element 0 $v)
       (tuple-index $element 1 $ij)
       (tuple-index $ij 0 $i)
       (tuple-index $ij 1 $j)
       (- $j $b $j-b)
       (+ $j-b $a $new-j)
       (- $i $a $i-a)
       (+ $i-a $b $new-i)
       (make-tuple ($new-j $new-i) $new-coords) ;; Extracted new coordinates into a separate statement
       (make-tuple ($v $new-coords) $new-element) ;; Use the extracted variable
       (collect $new-element $new-elements))
     (make-frozenset $new-elements $output)))

;; Extracted new coordinates into a separate statement
(= (dmirror $piece $output)
   (match-and &self
     "mirroring along diagonal"
     (not (is-tuple $piece))
     (ulcorner $piece $a $b)
     (length $piece $len)
     (match-all &self
       "iterate over elements"
       (range 0 $len 1 $i)
       (tuple-index $piece $i $ij)
       (tuple-index $ij 0 $i)
       (tuple-index $ij 1 $j)
       (- $j $b $j-b)
       (+ $j-b $a $new-j)
       (- $i $a $i-a)
       (+ $i-a $b $new-i)
       (make-tuple ($new-j $new-i) $new-element)
       (collect $new-element $new-elements))
     (make-frozenset $new-elements $output)))

;; def cmirror(piece: Piece) -> Piece: ;; """ mirroring along counterdiagonal """ ;; if isinstance(piece, tuple): ;; return tuple(zip(*(r[::-1] for r in piece[::-1]))) ;; return vmirror(dmirror(vmirror(piece)))

;; Case when $piece is a tuple
(= (cmirror $piece $output)
   (match-and &self
     "mirroring along counterdiagonal"
     (is-tuple $piece)
     (length $piece $len)
     (match-all &self
       "reverse rows"
       (range 0 $len 1 $i)
       (tuple-index $piece $i $r)
       (reverse $r $reversed-r)
       (collect $reversed-r $reversed-rows))
     (reverse $reversed-rows $reversed-rows-reversed)
     (transpose $reversed-rows-reversed $transposed)
     (make-tuple $transposed $output)))

;; Case when $piece is not a tuple
(= (cmirror $piece $output)
   (match-and &self
     "mirroring along counterdiagonal"
     (not (is-tuple $piece))
     (vmirror $piece $vmirrored1)
     (dmirror $vmirrored1 $dmirrored)
     (vmirror $dmirrored $output)))

;; def fill(grid: Grid, value: Integer, patch: Patch) -> Grid: ;; """ fill value at indices """ ;; h, w = (len(grid), len(grid[0])) ;; grid_filled = list((list(row) for row in grid)) ;; for i, j in toindices(patch): ;; if 0 <= i < h and 0 <= j < w: ;; grid_filled[i][j] = value ;; return tuple((tuple(row) for row in grid_filled))

(= (fill $grid $value $patch $output)
   (match-and &self
     "fill value at indices"
     (length $grid $h)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     (map $grid list-helper $grid-filled)
     (toindices $patch $indices)
     (length $indices $indices-len)
     (match-all &self
       "iterate over indices"
       (range 0 $indices-len 1 $k)
       (tuple-index $indices $k $index)
       (tuple-index $index 0 $i)
       (tuple-index $index 1 $j)
       (>= $i 0)
       (< $i $h)
       (>= $j 0)
       (< $j $w)
       (tuple-index $grid-filled $i $row)
       (set-tuple-index $row $j $value $new-row)
       (set-tuple-index $grid-filled $i $new-row $grid-filled)))
     (map $grid-filled tuple-helper $output)))

;; Extracted the condition where $i and $j are within bounds into separate statements
(= (fill $grid $value $patch $output)
   (match-and &self
     "fill value at indices"
     (length $grid $h)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     (map $grid list-helper $grid-filled)
     (toindices $patch $indices)
     (length $indices $indices-len)
     (match-all &self
       "iterate over indices"
       (range 0 $indices-len 1 $k)
       (tuple-index $indices $k $index)
       (tuple-index $index 0 $i)
       (tuple-index $index 1 $j)
       (>= $i 0)
       (< $i $h)
       ;; $i is within bounds
       (match-and &self
         "check if $j is within bounds"
         (>= $j 0)
         (< $j $w)
         (tuple-index $grid-filled $i $row)
         (set-tuple-index $row $j $value $new-row)
         (set-tuple-index $grid-filled $i $new-row $grid-filled))))
     (map $grid-filled tuple-helper $output)))

(= (list-helper $row $out)
   (match-and &self
     "convert row to list"
     (make-list $row $out)))

(= (tuple-helper $row $out)
   (match-and &self
     "convert row to tuple"
     (make-tuple $row $out)))

;; def paint(grid: Grid, obj: Object) -> Grid: ;; """ paint object to grid """ ;; h, w = (len(grid), len(grid[0])) ;; grid_painted = list((list(row) for row in grid)) ;; for value, (i, j) in obj: ;; if 0 <= i < h and 0 <= j < w: ;; grid_painted[i][j] = value ;; return tuple((tuple(row) for row in grid_painted))

;; Extracted $first-row into a separate statement
(= (paint $grid $obj $output)
   (match-and &self
     "paint object to grid"
     (length $grid $h)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     (map $grid list-helper $grid-list)
     (length $obj $len-obj)
     (match-all &self
       "iterate over object elements"
       (range 0 $len-obj 1 $k)
       (tuple-index $obj $k $pair)
       (tuple-index $pair 0 $value)
       (tuple-index $pair 1 $coords)
       (tuple-index $coords 0 $i)
       (tuple-index $coords 1 $j)
       ;; Extracted condition into a separate statement
       (and (>= $i 0) (< $i $h) (>= $j 0) (< $j $w) $condition)
       (if $condition
           (match-and &self
             "update grid"
             (tuple-index $grid-list $i $row)
             (tuple-index $row $j $old-value)
             (replace-index $row $j $value $new-row)
             (replace-index $grid-list $i $new-row $grid-list))))
     (map $grid-list tuple-helper $output)))

(= (list-helper $row $out)
   (match-and &self
     "convert row to list"
     (make-list $row $out)))

(= (tuple-helper $row $out)
   (match-and &self
     "convert row to tuple"
     (make-tuple $row $out)))

;; def underfill(grid: Grid, value: Integer, patch: Patch) -> Grid: ;; """ fill value at indices that are background """ ;; h, w = (len(grid), len(grid[0])) ;; bg = mostcolor(grid) ;; g = list((list(r) for r in grid)) ;; for i, j in toindices(patch): ;; if 0 <= i < h and 0 <= j < w: ;; if g[i][j] == bg: ;; g[i][j] = value ;; return tuple((tuple(r) for r in g))

(= (underfill $grid $value $patch $output)
   (match-and &self
     "fill value at indices that are background"
     (length $grid $h)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     (mostcolor $grid $bg)
     (map $grid list-helper $g)
     (match-all &self
       "iterate over patch indices"
       (toindices $patch $indices)
       (length $indices $len-indices)
       (range 0 $len-indices 1 $k)
       (tuple-index $indices $k $index)
       (tuple-index $index 0 $i)
       (tuple-index $index 1 $j)
       (>= $i 0)
       (< $i $h)
       (>= $j 0)
       (< $j $w)
       (tuple-index $g $i $row)
       (tuple-index $row $j $cell)
       (== $cell $bg)
       ;; Extracted set-tuple-index into separate statements
       (set-tuple-index $row $j $value $new-row)
       (set-tuple-index $g $i $new-row $new-g)))
     ;; Use the extracted variable
     (map $new-g tuple-helper $output)))

(= (list-helper $row $out)
   (match-and &self
     "convert row to list"
     (make-list $row $out)))

(= (tuple-helper $row $out)
   (match-and &self
     "convert row to tuple"
     (make-tuple $row $out)))

;; def underpaint(grid: Grid, obj: Object) -> Grid: ;; """ paint object to grid where there is background """ ;; h, w = (len(grid), len(grid[0])) ;; bg = mostcolor(grid) ;; g = list((list(r) for r in grid)) ;; for value, (i, j) in obj: ;; if 0 <= i < h and 0 <= j < w: ;; if g[i][j] == bg: ;; g[i][j] = value ;; return tuple((tuple(r) for r in g))

(= (underpaint $grid $obj $output)
   (match-and &self
     "paint object to grid where there is background"
     (length $grid $h)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     (mostcolor $grid $bg)
     (map $grid to-list $g)
     (match-all &self
       "iterate over object elements"
       (length $obj $obj-length) ;; Extracted length of object into a separate statement
       (range 0 $obj-length 1 $k) ;; Use the extracted variable
       (tuple-index $obj $k $pair)
       (tuple-index $pair 0 $value)
       (tuple-index $pair 1 $indices)
       (tuple-index $indices 0 $i)
       (tuple-index $indices 1 $j)
       (match-and &self
         "check bounds and background"
         (>= $i 0)
         (< $i $h)
         (>= $j 0)
         (< $j $w)
         (tuple-index $g $i $row)
         (tuple-index $row $j $cell)
         (== $cell $bg)
         (set-tuple-index $row $j $value $new-row)
         (set-tuple-index $g $i $new-row $g)))
     (map $g to-tuple $output)))

;; def hupscale(grid: Grid, factor: Integer) -> Grid: ;; """ upscale grid horizontally """ ;; g = tuple() ;; for row in grid: ;; r = tuple() ;; for value in row: ;; r = r + tuple((value for num in range(factor))) ;; g = g + (r,) ;; return g

(= (hupscale $grid $factor $output)
   (match-and &self
     "upscale grid horizontally"
     (make-tuple () $empty-tuple)
     (assign $empty-tuple $g)
     (length $grid $len-grid)
     (match-all &self
       "iterate over rows"
       (range 0 $len-grid 1 $i)
       (tuple-index $grid $i $row)
       (assign $empty-tuple $r)
       (length $row $len-row)
       (match-all &self
         "iterate over values in row"
         (range 0 $len-row 1 $j)
         (tuple-index $row $j $value)
         (match-all &self
           "repeat value factor times"
           (range 0 $factor 1 $num)
           (collect $value $repeated-values))
         (make-tuple $repeated-values $repeated-tuple)
         (concat $r $repeated-tuple $r)))
       (make-tuple ($r) $r-tuple)
       (concat $g $r-tuple $g))
     (var $output $g)))

;; Extracted repeated-values into a separate statement
(= (hupscale $grid $factor $output)
   (match-and &self
     "upscale grid horizontally"
     (make-tuple () $empty-tuple)
     (assign $empty-tuple $g)
     (length $grid $len-grid)
     (match-all &self
       "iterate over rows"
       (range 0 $len-grid 1 $i)
       (tuple-index $grid $i $row)
       (assign $empty-tuple $r)
       (length $row $len-row)
       (match-all &self
         "iterate over values in row"
         (range 0 $len-row 1 $j)
         (tuple-index $row $j $value)
         (match-all &self
           "repeat value factor times"
           (range 0 $factor 1 $num)
           (collect $value $repeated-values))
         (make-tuple $repeated-values $repeated-tuple)
         (concat $r $repeated-tuple $r)))
       (make-tuple ($r) $r-tuple)
       (concat $g $r-tuple $g))
     (var $output $g)))

;; def vupscale(grid: Grid, factor: Integer) -> Grid: ;; """ upscale grid vertically """ ;; g = tuple() ;; for row in grid: ;; g = g + tuple((row for num in range(factor))) ;; return g

;; Extracted empty tuple into a separate statement
(= (vupscale $grid $factor $output)
   (match-and &self
     "upscale grid vertically"
     (make-tuple () $g) ;; Extracted empty tuple into a separate statement
     (length $grid $len)
     (match-all &self
       "iterate over rows"
       (range 0 $len 1 $i)
       (tuple-index $grid $i $row)
       (match-all &self
         "repeat row factor times"
         (range 0 $factor 1 $num)
         (collect $row $repeated-rows)))
     (make-tuple $repeated-rows $repeated-tuple) ;; Extracted repeated rows into a separate statement
     (concat $g $repeated-tuple $output))) ;; Use the extracted variable

;; def upscale(element: Element, factor: Integer) -> Element: ;; """ upscale object or grid """ ;; if isinstance(element, tuple): ;; g = tuple() ;; for row in element: ;; upscaled_row = tuple() ;; for value in row: ;; upscaled_row = upscaled_row + tuple((value for num in range(factor))) ;; g = g + tuple((upscaled_row for num in range(factor))) ;; return g ;; else: ;; if len(element) == 0: ;; return frozenset() ;; di_inv, dj_inv = ulcorner(element) ;; di, dj = (-di_inv, -dj_inv) ;; normed_obj = shift(element, (di, dj)) ;; o = set() ;; for value, (i, j) in normed_obj: ;; for io in range(factor): ;; for jo in range(factor): ;; o.add((value, (i * factor + io, j * factor + jo))) ;; return shift(frozenset(o), (di_inv, dj_inv))

;; Extracted $upscaled-value into a separate statement
(= (upscale $element $factor $output)
   (match-and &self
     "upscale object or grid"
     (is-tuple $element)
     (make-tuple () $g)
     (length $element $len)
     (match-all &self
       "iterate over rows"
       (range 0 $len 1 $i)
       (tuple-index $element $i $row)
       (make-tuple () $upscaled-row)
       (length $row $len-row)
       (match-all &self
         "iterate over values in row"
         (range 0 $len-row 1 $j)
         (tuple-index $row $j $value)
         (match-all &self
           "upscale value"
           (range 0 $factor 1 $num)
           (collect $value $upscaled-value))
         (make-tuple $upscaled-value $upscaled-row))) ;; Use the extracted variable
       (match-all &self
         "upscale row"
         (range 0 $factor 1 $num)
         (collect $upscaled-row $upscaled-rows))
       (make-tuple $upscaled-rows $g))
     (assign $g $output)))

;; $element is not a tuple and length is 0 (became a separate statement)
(= (upscale $element $factor $output)
   (match-and &self
     "upscale object or grid"
     (not (is-tuple $element))
     (length $element 0)
     (make-frozenset () $output)))

;; $element is not a tuple and length is not 0 (became a separate statement)
(= (upscale $element $factor $output)
   (match-and &self
     "upscale object or grid"
     (not (is-tuple $element))
     (not (length $element 0))
     (ulcorner $element $di-inv $dj-inv)
     (- 0 $di-inv $di)
     (- 0 $dj-inv $dj)
     (shift $element (make-tuple ($di $dj)) $normed-obj)
     (make-set () $o)
     (length $normed-obj $len-normed)
     (match-all &self
       "iterate over normed object"
       (range 0 $len-normed 1 $i)
       (tuple-index $normed-obj $i $pair)
       (tuple-index $pair 0 $value)
       (tuple-index $pair 1 $coords)
       (tuple-index $coords 0 $i)
       (tuple-index $coords 1 $j)
       (match-all &self
         "upscale coordinates"
         (range 0 $factor 1 $io)
         (range 0 $factor 1 $jo)
         (* $i $factor $i-factor)
         (+ $i-factor $io $i-new)
         (* $j $factor $j-factor)
         (+ $j-factor $jo $j-new)
         (make-tuple ($i-new $j-new) $new-coords) ;; Extracted new coordinates into a separate statement
         (make-tuple ($value $new-coords) $new-pair) ;; Use the extracted variable
         (collect $new-pair $o)))
     (make-frozenset $o $frozenset-o)
     (shift $frozenset-o (make-tuple ($di-inv $dj-inv)) $output)))

;; def downscale(grid: Grid, factor: Integer) -> Grid: ;; """ downscale grid """ ;; h, w = (len(grid), len(grid[0])) ;; g = tuple() ;; for i in range(h): ;; r = tuple() ;; for j in range(w): ;; if j % factor == 0: ;; r = r + (grid[i][j],) ;; g = g + (r,) ;; h = len(g) ;; dsg = tuple() ;; for i in range(h): ;; if i % factor == 0: ;; dsg = dsg + (g[i],) ;; return dsg

(= (downscale $grid $factor $output)
   (match-and &self
     "downscale grid"
     (length $grid $h)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     (make-tuple () $empty-tuple)
     (match-all &self
       "iterate over rows"
       (range 0 $h 1 $i)
       (tuple-index $grid $i $row)
       (make-tuple () $empty-row)
       (match-all &self
         "iterate over columns"
         (range 0 $w 1 $j)
         (tuple-index $row $j $val)
         (mod $j $factor $mod-j)
         (== $mod-j 0)
         (collect $val $new-row))
       (make-tuple $new-row $r)
       (collect $r $g))
     (length $g $new-h)
     (make-tuple () $empty-dsg)
     (match-all &self
       "downscale rows"
       (range 0 $new-h 1 $i)
       (tuple-index $g $i $row)
       (mod $i $factor $mod-i)
       (== $mod-i 0)
       (collect $row $dsg))
     (make-tuple $dsg $output)))

;; $grid is downscaled and $output is assigned (became a separate statement)
(= (downscale $grid $factor $output)
   (match-and &self
     "downscale grid"
     (length $grid $h)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     (make-tuple () $empty-tuple)
     (match-all &self
       "iterate over rows"
       (range 0 $h 1 $i)
       (tuple-index $grid $i $row)
       (make-tuple () $empty-row)
       (match-all &self
         "iterate over columns"
         (range 0 $w 1 $j)
         (tuple-index $row $j $val)
         (mod $j $factor $mod-j)
         (== $mod-j 0)
         (collect $val $new-row))
       (make-tuple $new-row $r)
       (collect $r $g))
     (length $g $new-h)
     (make-tuple () $empty-dsg)
     (match-all &self
       "downscale rows"
       (range 0 $new-h 1 $i)
       (tuple-index $g $i $row)
       (mod $i $factor $mod-i)
       (== $mod-i 0)
       (collect $row $dsg))
     (make-tuple $dsg $output)))

;; def hconcat(a: Grid, b: Grid) -> Grid: ;; """ concatenate two grids horizontally """ ;; return tuple((i + j for i, j in zip(a, b)))

(= (hconcat $a $b $output)
   (match-and &self
     "concatenate two grids horizontally"
     (length $a $len)
     (match-all &self
       "iterate over rows"
       (range 0 $len 1 $i)
       (tuple-index $a $i $row-a)
       (tuple-index $b $i $row-b)
       (concat $row-a $row-b $new-row)
       (collect $new-row $new-rows))
     (make-tuple $new-rows $output))) ;; No changes needed, already extracted intermediate expressions

;; def vconcat(a: Grid, b: Grid) -> Grid: ;; """ concatenate two grids vertically """ ;; return a + b

;; Extracted intermediate expression into a separate statement
(= (vconcat $a $b $output)
   (match-and &self
     "concatenate two grids vertically"
     (make-tuple ($a $b) $result)
     (flatten $result $flattened-result) ;; Extracted flatten result into a separate statement
     (var $output $flattened-result))) ;; Use the extracted variable

;; def subgrid(patch: Patch, grid: Grid) -> Grid: ;; """ smallest subgrid containing object """ ;; return crop(grid, ulcorner(patch), shape(patch))

;; Extracted $ulcorner and $shape into separate statements
(= (subgrid $patch $grid $output)
   (match-and &self
     "smallest subgrid containing object"
     (ulcorner $patch $ulcorner)
     (shape $patch $shape)
     (crop $grid $ulcorner $shape $output)))

;; def hsplit(grid: Grid, n: Integer) -> Tuple: ;; """ split grid horizontally """ ;; h, w = (len(grid), len(grid[0]) // n) ;; offset = len(grid[0]) % n != 0 ;; return tuple((crop(grid, (0, w * i + i * offset), (h, w)) for i in range(n)))

(= (hsplit $grid $n $output)
   (match-and &self
     "split grid horizontally"
     (length $grid $h)
     (tuple-index $grid 0 $first-row)
     (length $first-row $total-width)
     (/ $total-width $n $w)
     (% $total-width $n $remainder)
     (!= $remainder 0 $offset)
     (length $grid $h)
     (- $n 1 $n-1)
     (match-all &self
       "iterate over parts"
       (range 0 $n-1 1 $i)
       (* $w $i $wi)
       (* $i $offset $ioffset)
       (+ $wi $ioffset $start-x)
       (make-tuple (0 $start-x) $start)
       (make-tuple ($h $w) $size)
       (crop $grid $start $size $part)
       (collect $part $parts))
     (make-tuple $parts $output)))

;; Extracted the calculation of $wi into a separate statement
;; Extracted the calculation of $ioffset into a separate statement
;; Extracted the calculation of $start-x into a separate statement
;; Extracted the creation of $start into a separate statement
;; Extracted the creation of $size into a separate statement
;; Used the extracted variables in the subsequent statements

;; def vsplit(grid: Grid, n: Integer) -> Tuple: ;; """ split grid vertically """ ;; h, w = (len(grid) // n, len(grid[0])) ;; offset = len(grid) % n != 0 ;; hs = (h * i + i * offset,) ;; g = (crop(grid, (hs, 0), (h, w)),) ;; return tuple((g for i in range(n)))

(= (vsplit $grid $n $output)
   (match-and &self
     "split grid vertically"
     (length $grid $len-grid)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     (/ $len-grid $n $h)
     (% $len-grid $n $remainder)
     (not (== $remainder 0))
     (== $offset 1)
     (match-all &self
       "iterate over n parts"
       (range 0 $n 1 $i)
       (* $h $i $hi)
       (* $i $offset $offset-i)
       (+ $hi $offset-i $hs)
       (make-tuple $hs 0 $start)
       (make-tuple $h $w $size)
       (crop $grid $start $size $g)
       (collect $g $parts))
     (make-tuple $parts $output)))

;; Extracted $offset into a separate statement
(= (vsplit $grid $n $output)
   (match-and &self
     "split grid vertically"
     (length $grid $len-grid)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     (/ $len-grid $n $h)
     (% $len-grid $n $remainder)
     (not (== $remainder 0))
     (var $offset 1) ;; Extracted $offset as a separate variable
     (match-all &self
       "iterate over n parts"
       (range 0 $n 1 $i)
       (* $h $i $hi)
       (* $i $offset $offset-i)
       (+ $hi $offset-i $hs)
       (make-tuple $hs 0 $start)
       (make-tuple $h $w $size)
       (crop $grid $start $size $g)
       (collect $g $parts))
     (make-tuple $parts $output)))

;; def cellwise(a: Grid, b: Grid, fallback: Integer) -> Grid: ;; """ cellwise match of two grids """ ;; h, w = (len(a), len(a[0])) ;; resulting_grid = tuple() ;; for i in range(h): ;; row = tuple() ;; for j in range(w): ;; a_value = a[i][j] ;; value = a_value if a_value == b[i][j] else fallback ;; row = row + (value,) ;; resulting_grid = resulting_grid + (row,) ;; return resulting_grid

;; Extracted length of first row into a separate statement
(= (cellwise $a $b $fallback $output)
   (match-and &self
     "cellwise match of two grids"
     (length $a $h)
     (tuple-index $a 0 $first-row)
     (length $first-row $w)
     (match-all &self
       "iterate over rows"
       (range 0 $h 1 $i)
       (tuple-index $a $i $a-row)
       (tuple-index $b $i $b-row)
       (length $a-row $len-row)
       (make-tuple () $row)
       (match-all &self
         "iterate over columns"
         (range 0 $w 1 $j)
         (tuple-index $a-row $j $a-value)
         (tuple-index $b-row $j $b-value)
         ;; Extracted equality check into a separate statement
         (== $a-value $b-value $is-equal)
         ;; Extracted if statement into a separate statement
         (if $is-equal $a-value $fallback $value)
         (append $row $value $new-row)
         (set $row $new-row))
       (append $resulting-grid $row $new-resulting-grid)
       (set $resulting-grid $new-resulting-grid))
     (set $output $resulting-grid)))

;; def replace(grid: Grid, replacee: Integer, replacer: Integer) -> Grid: ;; """ color substitution """ ;; return tuple((tuple((replacer if v == replacee else v for v in r)) for r in grid))

;; Extracted $v replacement logic into separate statements
(= (replace $grid $replacee $replacer $output)
   (match-and &self
     "color substitution"
     (length $grid $len)
     (match-all &self
       "iterate over rows"
       (range 0 $len 1 $i)
       (tuple-index $grid $i $r)
       (length $r $len-r)
       (match-all &self
         "iterate over values in row"
         (range 0 $len-r 1 $j)
         (tuple-index $r $j $v)
         ;; Check if $v equals $replacee and assign $replacer
         (match-and &self
           "replace value if equal"
           (== $v $replacee)
           (var $replaced-value $replacer))
         ;; Check if $v does not equal $replacee and keep $v
         (match-and &self
           "keep value if not equal"
           (not (== $v $replacee))
           (var $replaced-value $v))
         (collect $replaced-value $new-row))) ;; Use the extracted variable
       (make-tuple $new-row $new-r))
     (make-tuple $new-r $output)))

;; def switch(grid: Grid, a: Integer, b: Integer) -> Grid: ;; """ color switching """ ;; return tuple((tuple((v if v != a and v != b else {a: b, b: a}[v] for v in r)) for r in grid))

;; Extracted switch map and new value into separate statements
(= (switch $grid $a $b $output)
   (match-and &self
     "color switching"
     (length $grid $len)
     (match-all &self
       "iterate over rows"
       (range 0 $len 1 $i)
       (tuple-index $grid $i $r)
       (length $r $len-r)
       (match-all &self
         "iterate over values in row"
         (range 0 $len-r 1 $j)
         (tuple-index $r $j $v)
         (match-and &self
           "check if value needs switching"
           (or (== $v $a) (== $v $b))
           (make-tuple ($a $b) ($b $a) $switch-map) ;; Extracted switch map
           (tuple-index $switch-map $v $new-v) ;; Extracted new value
           (collect $new-v $new-row))
         (match-and &self
           "value does not need switching"
           (not (or (== $v $a) (== $v $b)))
           (collect $v $new-row)))
       (make-tuple $new-row $new-r))
     (make-tuple $new-r $output)))

;; def center(patch: Patch) -> IntegerTuple: ;; """ center of the patch """ ;; return (uppermost(patch) + height(patch) // 2, leftmost(patch) + width(patch) // 2)

;; Extracted half-height calculation into a separate statement
(= (center $patch $output)
   (match-and &self
     "center of the patch"
     (uppermost $patch $upper)
     (height $patch $height)
     (// $height 2 $half-height)
     (+ $upper $half-height $center-y)))
;; Extracted half-width calculation into a separate statement
(= (center $patch $output)
   (match-and &self
     "center of the patch"
     (leftmost $patch $left)
     (width $patch $width)
     (// $width 2 $half-width)
     (+ $left $half-width $center-x)))
;; Combined the calculated center coordinates into a tuple
(= (center $patch $output)
   (match-and &self
     "center of the patch"
     (make-tuple ($center-y $center-x) $output)))

;; def position(a: Patch, b: Patch) -> IntegerTuple: ;; """ relative position between two patches """ ;; ia, ja = center(toindices(a)) ;; ib, jb = center(toindices(b)) ;; if ia == ib: ;; return (0, 1 if ja < jb else -1) ;; elif ja == jb: ;; return (1 if ia < ib else -1, 0) ;; elif ia < ib: ;; return (1, 1 if ja < jb else -1) ;; elif ia > ib: ;; return (-1, 1 if ja < jb else -1)

;; Extracted common operations into separate statements
(= (position $a $b $output)
   (match-and &self
     "relative position between two patches"
     (toindices $a $indices-a)
     (toindices $b $indices-b)
     (center $indices-a $center-a)
     (center $indices-b $center-b)
     (tuple-index $center-a 0 $ia)
     (tuple-index $center-a 1 $ja)
     (tuple-index $center-b 0 $ib)
     (tuple-index $center-b 1 $jb)
     (== $ia $ib)
     (match-and &self
       "same row"
       (< $ja $jb)
       (make-tuple (0 1) $output))))

;; Extracted common operations into separate statements
(= (position $a $b $output)
   (match-and &self
     "relative position between two patches"
     (toindices $a $indices-a)
     (toindices $b $indices-b)
     (center $indices-a $center-a)
     (center $indices-b $center-b)
     (tuple-index $center-a 0 $ia)
     (tuple-index $center-a 1 $ja)
     (tuple-index $center-b 0 $ib)
     (tuple-index $center-b 1 $jb)
     (== $ia $ib)
     (match-and &self
       "same row"
       (>= $ja $jb)
       (make-tuple (0 -1) $output))))

;; Extracted common operations into separate statements
(= (position $a $b $output)
   (match-and &self
     "relative position between two patches"
     (toindices $a $indices-a)
     (toindices $b $indices-b)
     (center $indices-a $center-a)
     (center $indices-b $center-b)
     (tuple-index $center-a 0 $ia)
     (tuple-index $center-a 1 $ja)
     (tuple-index $center-b 0 $ib)
     (tuple-index $center-b 1 $jb)
     (== $ja $jb)
     (match-and &self
       "same column"
       (< $ia $ib)
       (make-tuple (1 0) $output))))

;; Extracted common operations into separate statements
(= (position $a $b $output)
   (match-and &self
     "relative position between two patches"
     (toindices $a $indices-a)
     (toindices $b $indices-b)
     (center $indices-a $center-a)
     (center $indices-b $center-b)
     (tuple-index $center-a 0 $ia)
     (tuple-index $center-a 1 $ja)
     (tuple-index $center-b 0 $ib)
     (tuple-index $center-b 1 $jb)
     (== $ja $jb)
     (match-and &self
       "same column"
       (>= $ia $ib)
       (make-tuple (-1 0) $output))))

;; Extracted common operations into separate statements
(= (position $a $b $output)
   (match-and &self
     "relative position between two patches"
     (toindices $a $indices-a)
     (toindices $b $indices-b)
     (center $indices-a $center-a)
     (center $indices-b $center-b)
     (tuple-index $center-a 0 $ia)
     (tuple-index $center-a 1 $ja)
     (tuple-index $center-b 0 $ib)
     (tuple-index $center-b 1 $jb)
     (< $ia $ib)
     (match-and &self
       "below"
       (< $ja $jb)
       (make-tuple (1 1) $output))))

;; Extracted common operations into separate statements
(= (position $a $b $output)
   (match-and &self
     "relative position between two patches"
     (toindices $a $indices-a)
     (toindices $b $indices-b)
     (center $indices-a $center-a)
     (center $indices-b $center-b)
     (tuple-index $center-a 0 $ia)
     (tuple-index $center-a 1 $ja)
     (tuple-index $center-b 0 $ib)
     (tuple-index $center-b 1 $jb)
     (< $ia $ib)
     (match-and &self
       "below"
       (>= $ja $jb)
       (make-tuple (1 -1) $output))))

;; Extracted common operations into separate statements
(= (position $a $b $output)
   (match-and &self
     "relative position between two patches"
     (toindices $a $indices-a)
     (toindices $b $indices-b)
     (center $indices-a $center-a)
     (center $indices-b $center-b)
     (tuple-index $center-a 0 $ia)
     (tuple-index $center-a 1 $ja)
     (tuple-index $center-b 0 $ib)
     (tuple-index $center-b 1 $jb)
     (> $ia $ib)
     (match-and &self
       "above"
       (< $ja $jb)
       (make-tuple (-1 1) $output))))

;; Extracted common operations into separate statements
(= (position $a $b $output)
   (match-and &self
     "relative position between two patches"
     (toindices $a $indices-a)
     (toindices $b $indices-b)
     (center $indices-a $center-a)
     (center $indices-b $center-b)
     (tuple-index $center-a 0 $ia)
     (tuple-index $center-a 1 $ja)
     (tuple-index $center-b 0 $ib)
     (tuple-index $center-b 1 $jb)
     (> $ia $ib)
     (match-and &self
       "above"
       (>= $ja $jb)
       (make-tuple (-1 -1) $output))))

;; def index(grid: Grid, loc: IntegerTuple) -> Integer: ;; """ color at location """ ;; i, j = loc ;; h, w = (len(grid), len(grid[0])) ;; if not (0 <= i < h and 0 <= j < w): ;; return None ;; return grid[loc[0]][loc[1]]

;; Extracted $i and $j from $loc into separate statements
(= (index $grid $loc $output)
   (match-and &self
     "color at location"
     (tuple-index $loc 0 $i)
     (tuple-index $loc 1 $j)
     (length $grid $h)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     ;; $i and $j are within bounds (became a separate statement)
     (match-and &self
       "check bounds"
       (>= $i 0)
       (< $i $h)
       (>= $j 0)
       (< $j $w)
       (tuple-index $grid $i $row)
       (tuple-index $row $j $output)))
;; $i or $j are out of bounds (became a separate statement)
(= (index $grid $loc $output)
   (match-and &self
     "color at location"
     (tuple-index $loc 0 $i)
     (tuple-index $loc 1 $j)
     (length $grid $h)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     (match-and &self
       "out of bounds"
       (or (< $i 0) (>= $i $h) (< $j 0) (>= $j $w))
       (var $output None))))

;; def canvas(value: Integer, dimensions: IntegerTuple) -> Grid: ;; """ grid construction """ ;; return tuple((tuple((value for j in range(dimensions[1]))) for i in range(dimensions[0])))

(= (canvas $value $dimensions $output)
   (match-and &self
     "grid construction"
     (tuple-index $dimensions 0 $dim0)
     (tuple-index $dimensions 1 $dim1)
     (match-all &self
       "iterate over rows"
       (range 0 $dim0 1 $i)
       (match-all &self
         "iterate over columns"
         (range 0 $dim1 1 $j)
         (collect $value $row)))
     (make-tuple $row $new-row) ;; Extracted new row creation into a separate statement
     (collect $new-row $grid))
   (make-tuple $grid $output))) ;; Extracted grid creation into a separate statement

;; def corners(patch: Patch) -> Indices: ;; """ indices of corners """ ;; return frozenset({ulcorner(patch), urcorner(patch), llcorner(patch), lrcorner(patch)})

;; Extracted each corner into separate statements
(= (corners $patch $output)
   (match-and &self
     "indices of corners"
     (ulcorner $patch $ul)
     (urcorner $patch $ur)
     (llcorner $patch $ll)
     (lrcorner $patch $lr)
     (make-tuple ($ul $ur $ll $lr) $corners) ;; Extracted corners into a separate statement
     (make-frozenset $corners $output))) ;; Use the extracted variable

;; def connect(a: IntegerTuple, b: IntegerTuple) -> Indices: ;; """ line between two points """ ;; ai, aj = a ;; bi, bj = b ;; si = min(ai, bi) ;; ei = max(ai, bi) + 1 ;; sj = min(aj, bj) ;; ej = max(aj, bj) + 1 ;; if ai == bi: ;; return frozenset(((ai, j) for j in range(sj, ej))) ;; elif aj == bj: ;; return frozenset(((i, aj) for i in range(si, ei))) ;; elif bi - ai == bj - aj: ;; return frozenset(((i, j) for i, j in zip(range(si, ei), range(sj, ej)))) ;; elif bi - ai == aj - bj: ;; return frozenset(((i, j) for i, j in zip(range(si, ei), range(ej - 1, sj - 1, -1)))) ;; return frozenset()

;; Extracted $max-ai-bi and $max-aj-bj into separate statements
(= (connect $a $b $output)
   (match-and &self
     "line between two points"
     (tuple-index $a 0 $ai)
     (tuple-index $a 1 $aj)
     (tuple-index $b 0 $bi)
     (tuple-index $b 1 $bj)
     (min $ai $bi $si)
     (max $ai $bi $max-ai-bi)
     (+ $max-ai-bi 1 $ei)
     (min $aj $bj $sj)
     (max $aj $bj $max-aj-bj)
     (+ $max-aj-bj 1 $ej)
     ;; Vertical line case
     (match-and &self
       "vertical line"
       (== $ai $bi)
       (match-all &self
         "iterate over j"
         (range $sj $ej 1 $j)
         (make-tuple ($ai $j) $point)
         (collect $point $points))
       (make-frozenset $points $output)))
;; Horizontal line case
(= (connect $a $b $output)
   (match-and &self
     "line between two points"
     (tuple-index $a 0 $ai)
     (tuple-index $a 1 $aj)
     (tuple-index $b 0 $bi)
     (tuple-index $b 1 $bj)
     (min $ai $bi $si)
     (max $ai $bi $max-ai-bi)
     (+ $max-ai-bi 1 $ei)
     (min $aj $bj $sj)
     (max $aj $bj $max-aj-bj)
     (+ $max-aj-bj 1 $ej)
     (match-and &self
       "horizontal line"
       (== $aj $bj)
       (match-all &self
         "iterate over i"
         (range $si $ei 1 $i)
         (make-tuple ($i $aj) $point)
         (collect $point $points))
       (make-frozenset $points $output)))
;; Diagonal line 1 case
(= (connect $a $b $output)
   (match-and &self
     "line between two points"
     (tuple-index $a 0 $ai)
     (tuple-index $a 1 $aj)
     (tuple-index $b 0 $bi)
     (tuple-index $b 1 $bj)
     (min $ai $bi $si)
     (max $ai $bi $max-ai-bi)
     (+ $max-ai-bi 1 $ei)
     (min $aj $bj $sj)
     (max $aj $bj $max-aj-bj)
     (+ $max-aj-bj 1 $ej)
     (match-and &self
       "diagonal line 1"
       (== (- $bi $ai) (- $bj $aj))
       (match-all &self
         "iterate over i, j"
         (range $si $ei 1 $i)
         (range $sj $ej 1 $j)
         (make-tuple ($i $j) $point)
         (collect $point $points))
       (make-frozenset $points $output)))
;; Diagonal line 2 case
(= (connect $a $b $output)
   (match-and &self
     "line between two points"
     (tuple-index $a 0 $ai)
     (tuple-index $a 1 $aj)
     (tuple-index $b 0 $bi)
     (tuple-index $b 1 $bj)
     (min $ai $bi $si)
     (max $ai $bi $max-ai-bi)
     (+ $max-ai-bi 1 $ei)
     (min $aj $bj $sj)
     (max $aj $bj $max-aj-bj)
     (+ $max-aj-bj 1 $ej)
     (match-and &self
       "diagonal line 2"
       (== (- $bi $ai) (- $aj $bj))
       (match-all &self
         "iterate over i, j"
         (range $si $ei 1 $i)
         (range (- $ej 1) (- $sj 1) -1 $j)
         (make-tuple ($i $j) $point)
         (collect $point $points))
       (make-frozenset $points $output)))
;; Fall through case
(= (connect $a $b $output)
   (match-and &self
     "line between two points"
     (tuple-index $a 0 $ai)
     (tuple-index $a 1 $aj)
     (tuple-index $b 0 $bi)
     (tuple-index $b 1 $bj)
     (min $ai $bi $si)
     (max $ai $bi $max-ai-bi)
     (+ $max-ai-bi 1 $ei)
     (min $aj $bj $sj)
     (max $aj $bj $max-aj-bj)
     (+ $max-aj-bj 1 $ej)
     (make-frozenset () $output)))

;; def cover(grid: Grid, patch: Patch) -> Grid: ;; """ remove object from grid """ ;; return fill(grid, mostcolor(grid), toindices(patch))

;; Extracted mostcolor into a separate statement
(= (cover $grid $patch $output)
   (match-and &self
     "remove object from grid"
     (mostcolor $grid $most-color)
     (toindices $patch $indices)
     (fill $grid $most-color $indices $output)))

;; $grid is filled with most-color at indices (became a separate statement)
(= (cover $grid $patch $output)
   (match-and &self
     "remove object from grid"
     (mostcolor $grid $most-color)
     (toindices $patch $indices)
     (fill $grid $most-color $indices $output)))

;; def trim(grid: Grid) -> Grid: ;; """ trim border of grid """ ;; return tuple((r[1:-1] for r in grid[1:-1]))

(= (trim $grid $output)
   (match-and &self
     "trim border of grid"
     (length $grid $len)
     (- $len 1 $len-1)
     (match-all &self
       "iterate over rows excluding first and last"
       (range 1 $len-1 1 $i)
       (tuple-index $grid $i $r)
       (length $r $len-r)
       (- $len-r 1 $len-r-1)
       (match-all &self
         "trim row excluding first and last element"
         (range 1 $len-r-1 1 $j)
         (tuple-index $r $j $v)
         (collect $v $new-row))
       (make-tuple $new-row $trimmed-row) ;; Extracted new row into a separate statement
       (collect $trimmed-row $trimmed-rows)))
     (make-tuple $trimmed-rows $output))) ;; Extracted trimmed rows into a separate statement

;; def move(grid: Grid, obj: Object, offset: IntegerTuple) -> Grid: ;; """ move object on grid """ ;; return paint(cover(grid, obj), shift(obj, offset))

;; Extracted cover operation into a separate statement
(= (move $grid $obj $offset $output)
   (match-and &self
     "move object on grid"
     (cover $grid $obj $covered-grid))
;; Extracted shift operation into a separate statement
(= (move $grid $obj $offset $output)
   (match-and &self
     "move object on grid"
     (shift $obj $offset $shifted-obj))
;; Extracted paint operation into a separate statement
(= (move $grid $obj $offset $output)
   (match-and &self
     "move object on grid"
     (paint $covered-grid $shifted-obj $output)))

;; def tophalf(grid: Grid) -> Grid: ;; """ upper half of grid """ ;; return grid[:len(grid) // 2]

(= (tophalf $grid $output)
   (match-and &self
     "upper half of grid"
     (length $grid $len)
     (/ $len 2 $half-len)
     (- $half-len 1 $half-len-1)
     (match-all &self
       "iterate over upper half"
       (range 0 $half-len-1 1 $i)
       (tuple-index $grid $i $row)
       (collect $row $upper-half))
     (make-tuple $upper-half $output))) ;; No changes needed here as there's no nested function calls or multiple assignments to $output

;; def bottomhalf(grid: Grid) -> Grid: ;; """ lower half of grid """ ;; return grid[len(grid) // 2 + len(grid) % 2:]

;; Extracted half-length calculation into a separate statement
(= (bottomhalf $grid $output)
   (match-and &self
     "lower half of grid"
     (length $grid $len)
     (// $len 2 $half-len)
     (% $len 2 $remainder)
     (+ $half-len $remainder $start)
     (slice $grid $start $len $output)))

;; def lefthalf(grid: Grid) -> Grid: ;; """ left half of grid """ ;; return rot270(tophalf(rot90(grid)))

;; Extracted intermediate expressions into separate statements
(= (lefthalf $grid $output)
   (match-and &self
     "left half of grid"
     (rot90 $grid $rotated)
     (tophalf $rotated $top-half)
     (rot270 $top-half $rotated-back) ;; Extracted the result of rot270 into a separate variable
     (var $output $rotated-back))) ;; Use the extracted variable

;; def righthalf(grid: Grid) -> Grid: ;; """ right half of grid """ ;; return rot270(bottomhalf(rot90(grid)))

;; Extracted rotated grid into a separate statement
(= (righthalf $grid $output)
   (match-and &self
     "right half of grid"
     (rot90 $grid $rotated)
     (bottomhalf $rotated $bottom-half)
     (rot270 $bottom-half $output)))

;; Extracted bottom-half grid into a separate statement
(= (righthalf $grid $output)
   (match-and &self
     "right half of grid"
     (rot90 $grid $rotated)
     (bottomhalf $rotated $bottom-half)
     (rot270 $bottom-half $output)))

;; def vfrontier(location: IntegerTuple) -> Indices: ;; """ vertical frontier """ ;; return frozenset(((i, location[1]) for i in range(30)))

;; Extracted $y from tuple-index into a separate statement
(= (vfrontier $location $output)
   (match-and &self
     "vertical frontier"
     (tuple-index $location 1 $y)
     (match-all &self
       "iterate over range"
       (range 0 29 1 $i)
       (make-tuple ($i $y) $pair)
       (collect $pair $pairs))
     (make-frozenset $pairs $output)))

;; def hfrontier(location: IntegerTuple) -> Indices: ;; """ horizontal frontier """ ;; return frozenset(((location[0], j) for j in range(30)))

(= (hfrontier $location $output)
   (match-and &self
     "horizontal frontier"
     (tuple-index $location 0 $x)
     (match-all &self
       "iterate over indices"
       (range 0 29 1 $j)
       (make-tuple ($x $j) $t)
       (collect $t $tuples))
     (make-frozenset $tuples $output))) ;; No changes needed, as there are no nested function calls or multiple assignments to $output

;; def backdrop(patch: Patch) -> Indices: ;; """ indices in bounding box of patch """ ;; indices = toindices(patch) ;; si, sj = ulcorner(indices) ;; ei, ej = lrcorner(patch) ;; return frozenset(((i, j) for i in range(si, ei + 1) for j in range(sj, ej + 1)))

(= (backdrop $patch $output)
   (match-and &self
     "indices in bounding box of patch"
     (toindices $patch $indices)
     (ulcorner $indices $ulcorner)
     (tuple-index $ulcorner 0 $si)
     (tuple-index $ulcorner 1 $sj)
     (lrcorner $patch $lrcorner)
     (tuple-index $lrcorner 0 $ei)
     (tuple-index $lrcorner 1 $ej)
     (+ $ei 1 $ei1)
     (+ $ej 1 $ej1)
     (match-all &self
       "iterate over i"
       (range $si $ei1 1 $i)
       (match-all &self
         "iterate over j"
         (range $sj $ej1 1 $j)
         (make-tuple ($i $j) $index)
         (collect $index $indices-set)))
     (make-frozenset $indices-set $output)))

;; Extracted $ulcorner and $lrcorner into separate statements
(= (backdrop $patch $output)
   (match-and &self
     "indices in bounding box of patch"
     (toindices $patch $indices)
     (ulcorner $indices $ulcorner)
     (lrcorner $patch $lrcorner)
     ;; Extracted $si and $sj from $ulcorner
     (tuple-index $ulcorner 0 $si)
     (tuple-index $ulcorner 1 $sj)
     ;; Extracted $ei and $ej from $lrcorner
     (tuple-index $lrcorner 0 $ei)
     (tuple-index $lrcorner 1 $ej)
     ;; Calculated $ei1 and $ej1 separately
     (+ $ei 1 $ei1)
     (+ $ej 1 $ej1)
     (match-all &self
       "iterate over i"
       (range $si $ei1 1 $i)
       (match-all &self
         "iterate over j"
         (range $sj $ej1 1 $j)
         ;; Made $index a separate statement
         (make-tuple ($i $j) $index)
         (collect $index $indices-set)))
     (make-frozenset $indices-set $output)))

;; def delta(patch: Patch) -> Indices: ;; """ indices in bounding box but not part of patch """ ;; return backdrop(patch) - toindices(patch)

;; Extracted backdrop indices into a separate statement
(= (delta $patch $output)
   (match-and &self
     "indices in bounding box but not part of patch"
     (backdrop $patch $backdrop-indices)
     (toindices $patch $patch-indices)
     (- $backdrop-indices $patch-indices $delta-indices) ;; Extracted delta indices into a separate statement
     (var $output $delta-indices))) ;; Use the extracted variable

;; def gravitate(source: Patch, destination: Patch) -> IntegerTuple: ;; """ direction to move source until adjacent to destination """ ;; si, sj = center(source) ;; di, dj = center(destination) ;; i, j = (0, 0) ;; if vmatching(source, destination): ;; i = 1 if si < di else -1 ;; else: ;; j = 1 if sj < dj else -1 ;; gi, gj = (i, j) ;; c = 0 ;; while not adjacent(source, destination) and c < 42: ;; c += 1 ;; gi += i ;; gj += j ;; source = shift(source, (i, j)) ;; return (gi - i, gj - j)

;; Extracted $si and $sj into separate statements
;; Extracted $di and $dj into separate statements
;; Extracted $i and $j into separate statements
;; Extracted $gi and $gj into separate statements
(= (gravitate $source $destination $output)
   (match-and &self
     "direction to move source until adjacent to destination"
     (center $source $si-sj)
     (tuple-index $si-sj 0 $si)
     (tuple-index $si-sj 1 $sj)
     (center $destination $di-dj)
     (tuple-index $di-dj 0 $di)
     (tuple-index $di-dj 1 $dj)
     (make-tuple (0 0) $i-j)
     (tuple-index $i-j 0 $i)
     (tuple-index $i-j 1 $j)
     (vmatching $source $destination)
     (match-and &self
       "vmatching case"
       (< $si $di)
       (let $i 1))
     (match-and &self
       "vmatching case"
       (>= $si $di)
       (let $i -1))
     (not (vmatching $source $destination))
     (match-and &self
       "non-vmatching case"
       (< $sj $dj)
       (let $j 1))
     (match-and &self
       "non-vmatching case"
       (>= $sj $dj)
       (let $j -1))
     (make-tuple ($i $j) $gi-gj)
     (tuple-index $gi-gj 0 $gi)
     (tuple-index $gi-gj 1 $gj)
     (let $c 0)
     (gravitate-helper $source $destination $i $j $gi $gj $c $output)))

;; Extracted $new-c, $new-gi, and $new-gj into separate statements
;; Extracted $new-source into a separate statement
(= (gravitate-helper $source $destination $i $j $gi $gj $c $output)
   (match-and &self
     "recursive helper for gravitate"
     (not (adjacent $source $destination))
     (< $c 42)
     (+ $c 1 $new-c)
     (+ $gi $i $new-gi)
     (+ $gj $j $new-gj)
     (shift $source (make-tuple ($i $j)) $new-source)
     (gravitate-helper $new-source $destination $i $j $new-gi $new-gj $new-c $output)))

;; Extracted $final-gi and $final-gj into separate statements
(= (gravitate-helper $source $destination $i $j $gi $gj $c $output)
   (match-and &self
     "base case for gravitate"
     (or (adjacent $source $destination)
         (>= $c 42))
     (- $gi $i $final-gi)
     (- $gj $j $final-gj)
     (make-tuple ($final-gi $final-gj) $output)))

;; def inbox(patch: Patch) -> Indices: ;; """ inbox for patch """ ;; ai, aj = (uppermost(patch) + 1, leftmost(patch) + 1) ;; bi, bj = (lowermost(patch) - 1, rightmost(patch) - 1) ;; si, sj = (min(ai, bi), min(aj, bj)) ;; ei, ej = (max(ai, bi), max(aj, bj)) ;; vlines = {(i, sj) for i in range(si, ei + 1)} | {(i, ej) for i in range(si, ei + 1)} ;; hlines = {(si, j) for j in range(sj, ej + 1)} | {(ei, j) for j in range(sj, ej + 1)} ;; return frozenset(vlines | hlines)

;; Extract intermediate expressions into separate statements using temporary variables
(= (inbox $patch $output)
   (match-and &self
     "inbox for patch"
     (uppermost $patch $uppermost)
     (+ $uppermost 1 $ai)
     (leftmost $patch $leftmost)
     (+ $leftmost 1 $aj)
     (lowermost $patch $lowermost)
     (- $lowermost 1 $bi)
     (rightmost $patch $rightmost)
     (- $rightmost 1 $bj)
     (min $ai $bi $si)
     (min $aj $bj $sj)
     (max $ai $bi $ei)
     (max $aj $bj $ej)
     ;; Create vertical lines
     (match-all &self
       "create vertical lines"
       (range $si (+ $ei 1) 1 $i)
       (make-tuple ($i $sj) $vline1)
       (make-tuple ($i $ej) $vline2)
       (collect $vline1 $vlines)
       (collect $vline2 $vlines))
     ;; Create horizontal lines
     (match-all &self
       "create horizontal lines"
       (range $sj (+ $ej 1) 1 $j)
       (make-tuple ($si $j) $hline1)
       (make-tuple ($ei $j) $hline2)
       (collect $hline1 $hlines)
       (collect $hline2 $hlines))
     ;; Combine vertical and horizontal lines
     (union $vlines $hlines $lines)
     (make-frozenset $lines $output)))

;; $patch is int and uppermost (became a separate statement)
(= (inbox $patch $output)
   (match-and &self
     "inbox for patch"
     (uppermost $patch $uppermost)
     (+ $uppermost 1 $ai)
     (leftmost $patch $leftmost)
     (+ $leftmost 1 $aj)
     (lowermost $patch $lowermost)
     (- $lowermost 1 $bi)
     (rightmost $patch $rightmost)
     (- $rightmost 1 $bj)
     (min $ai $bi $si)
     (min $aj $bj $sj)
     (max $ai $bi $ei)
     (max $aj $bj $ej)
     ;; Create vertical lines
     (match-all &self
       "create vertical lines"
       (range $si (+ $ei 1) 1 $i)
       (make-tuple ($i $sj) $vline1)
       (make-tuple ($i $ej) $vline2)
       (collect $vline1 $vlines)
       (collect $vline2 $vlines))
     ;; Create horizontal lines
     (match-all &self
       "create horizontal lines"
       (range $sj (+ $ej 1) 1 $j)
       (make-tuple ($si $j) $hline1)
       (make-tuple ($ei $j) $hline2)
       (collect $hline1 $hlines)
       (collect $hline2 $hlines))
     ;; Combine vertical and horizontal lines
     (union $vlines $hlines $lines)
     (make-frozenset $lines $output)))

;; def outbox(patch: Patch) -> Indices: ;; """ outbox for patch """ ;; ai, aj = (uppermost(patch) - 1, leftmost(patch) - 1) ;; bi, bj = (lowermost(patch) + 1, rightmost(patch) + 1) ;; si, sj = (min(ai, bi), min(aj, bj)) ;; ei, ej = (max(ai, bi), max(aj, bj)) ;; vlines = {(i, sj) for i in range(si, ei + 1)} | {(i, ej) for i in range(si, ei + 1)} ;; hlines = {(si, j) for j in range(sj, ej + 1)} | {(ei, j) for j in range(sj, ej + 1)} ;; return frozenset(vlines | hlines)

;; Extracted $ei-plus1 calculation into a separate statement
(= (outbox $patch $output)
   (match-and &self
     "outbox for patch"
     (uppermost $patch $uppermost)
     (leftmost $patch $leftmost)
     (- $uppermost 1 $ai)
     (- $leftmost 1 $aj)
     (lowermost $patch $lowermost)
     (rightmost $patch $rightmost)
     (+ $lowermost 1 $bi)
     (+ $rightmost 1 $bj)
     (min $ai $bi $si)
     (min $aj $bj $sj)
     (max $ai $bi $ei)
     (max $aj $bj $ej)
     (+ $ei 1 $ei-plus1) ;; Extracted $ei-plus1 calculation
     (match-all &self
       "create vertical lines"
       (range $si $ei-plus1 1 $i)
       (make-tuple ($i $sj) $vline1)
       (make-tuple ($i $ej) $vline2)
       (collect $vline1 $vlines)
       (collect $vline2 $vlines))
     ;; Extracted $ej-plus1 calculation into a separate statement
     (+ $ej 1 $ej-plus1) ;; Extracted $ej-plus1 calculation
     (match-all &self
       "create horizontal lines"
       (range $sj $ej-plus1 1 $j)
       (make-tuple ($si $j) $hline1)
       (make-tuple ($ei $j) $hline2)
       (collect $hline1 $hlines)
       (collect $hline2 $hlines))
     (union $vlines $hlines $lines)
     (make-frozenset $lines $output)))

;; def box(patch: Patch) -> Indices: ;; """ outline of patch """ ;; ai, aj = ulcorner(patch) ;; bi, bj = lrcorner(patch) ;; si, sj = (min(ai, bi), min(aj, bj)) ;; ei, ej = (max(ai, bi), max(aj, bj)) ;; vlines = {(i, sj) for i in range(si, ei + 1)} | {(i, ej) for i in range(si, ei + 1)} ;; hlines = {(si, j) for j in range(sj, ej + 1)} | {(ei, j) for j in range(sj, ej + 1)} ;; return frozenset(vlines | hlines)

(= (box $patch $output)
   (match-and &self
     "outline of patch"
     (ulcorner $patch $ulcorner)
     (lrcorner $patch $lrcorner)
     (tuple-index $ulcorner 0 $ai)
     (tuple-index $ulcorner 1 $aj)
     (tuple-index $lrcorner 0 $bi)
     (tuple-index $lrcorner 1 $bj)
     (min $ai $bi $si)
     (min $aj $bj $sj)
     (max $ai $bi $ei)
     (max $aj $bj $ej)
     (match-all &self
       "vertical lines"
       (range $si (+ $ei 1) 1 $i)
       (make-tuple ($i $sj) $vline1)
       (make-tuple ($i $ej) $vline2)
       (collect $vline1 $vlines)
       (collect $vline2 $vlines))
     (match-all &self
       "horizontal lines"
       (range $sj (+ $ej 1) 1 $j)
       (make-tuple ($si $j) $hline1)
       (make-tuple ($ei $j) $hline2)
       (collect $hline1 $hlines)
       (collect $hline2 $hlines))
     (union $vlines $hlines $lines)
     (make-frozenset $lines $output)))

;; Separate the union and make-frozenset into separate statements
(= (box $patch $output)
   (match-and &self
     "outline of patch"
     (ulcorner $patch $ulcorner)
     (lrcorner $patch $lrcorner)
     (tuple-index $ulcorner 0 $ai)
     (tuple-index $ulcorner 1 $aj)
     (tuple-index $lrcorner 0 $bi)
     (tuple-index $lrcorner 1 $bj)
     (min $ai $bi $si)
     (min $aj $bj $sj)
     (max $ai $bi $ei)
     (max $aj $bj $ej)
     (match-all &self
       "vertical lines"
       (range $si (+ $ei 1) 1 $i)
       (make-tuple ($i $sj) $vline1)
       (make-tuple ($i $ej) $vline2)
       (collect $vline1 $vlines)
       (collect $vline2 $vlines))
     (match-all &self
       "horizontal lines"
       (range $sj (+ $ej 1) 1 $j)
       (make-tuple ($si $j) $hline1)
       (make-tuple ($ei $j) $hline2)
       (collect $hline1 $hlines)
       (collect $hline2 $hlines))
     (union $vlines $hlines $lines))
   (make-frozenset $lines $output))

;; def shoot(start: IntegerTuple, direction: IntegerTuple) -> Indices: ;; """ line from starting point and direction """ ;; return connect(start, (start[0] + 42 * direction[0], start[1] + 42 * direction[1]))

;; Extracted start-x and start-y into separate statements
(= (shoot $start $direction $output)
   (match-and &self
     "line from starting point and direction"
     (tuple-index $start 0 $start-x)
     (tuple-index $start 1 $start-y)
     ;; Extracted dir-x and dir-y into separate statements
     (tuple-index $direction 0 $dir-x)
     (tuple-index $direction 1 $dir-y)
     ;; Extracted scaled-dir-x and scaled-dir-y into separate statements
     (* $dir-x 42 $scaled-dir-x)
     (* $dir-y 42 $scaled-dir-y)
     ;; Extracted end-x and end-y into separate statements
     (+ $start-x $scaled-dir-x $end-x)
     (+ $start-y $scaled-dir-y $end-y)
     ;; Extracted end into a separate statement
     (make-tuple ($end-x $end-y) $end)
     (connect $start $end $output)))

;; def occurrences(grid: Grid, obj: Object) -> Indices: ;; """ locations of occurrences of object in grid """ ;; occs = set() ;; normed = normalize(obj) ;; h, w = (len(grid), len(grid[0])) ;; oh, ow = shape(obj) ;; h2, w2 = (h - oh + 1, w - ow + 1) ;; for i in range(h2): ;; for j in range(w2): ;; occurs = True ;; for v, (a, b) in shift(normed, (i, j)): ;; if not (0 <= a < h and 0 <= b < w and (grid[a][b] == v)): ;; occurs = False ;; break ;; if occurs: ;; occs.add((i, j)) ;; return frozenset(occs)

(= (occurrences $grid $obj $output)
   (match-and &self
     "locations of occurrences of object in grid"
     (normalize $obj $normed)
     (length $grid $h)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     (shape $obj $oh $ow)
     (- $h $oh 1 $h2)
     (- $w $ow 1 $w2)
     (match-all &self
       "iterate over possible positions"
       (range 0 $h2 1 $i)
       (range 0 $w2 1 $j)
       (make-tuple ($i $j) $pos) ;; Extracted position into a separate statement
       (shift $normed $pos $shifted) ;; Use the extracted variable
       (check-occurrence $shifted $grid $h $w $occurs)
       (== $occurs true)
       (collect $pos $occs)) ;; Use the extracted variable
     (make-frozenset $occs $output)))

(= (check-occurrence $shifted $grid $h $w $occurs)
   (match-and &self
     "check if object occurs at shifted position"
     (length $shifted $len)
     (match-all &self
       "iterate over shifted elements"
       (range 0 $len 1 $k)
       (tuple-index $shifted $k $pair)
       (tuple-index $pair 0 $v)
       (tuple-index $pair 1 $coords)
       (tuple-index $coords 0 $a)
       (tuple-index $coords 1 $b)
       (check-position $v $a $b $grid $h $w $valid)
       (== $valid true))
     (== $occurs true)))

;; $a is valid (became a separate statement)
(= (check-position $v $a $b $grid $h $w $valid)
   (match-and &self
     "check if position is valid"
     (<= 0 $a)
     (< $a $h)
     (<= 0 $b)
     (< $b $w)
     (tuple-index $grid $a $row)
     (tuple-index $row $b $grid-val)
     (== $grid-val $v)
     (== $valid true)))

;; $a is not valid (became a separate statement)
(= (check-position $v $a $b $grid $h $w $valid)
   (match-and &self
     "position is not valid"
     (not (<= 0 $a))
     (== $valid false)))

;; $a is not valid (became a separate statement)
(= (check-position $v $a $b $grid $h $w $valid)
   (match-and &self
     "position is not valid"
     (not (< $a $h))
     (== $valid false)))

;; $b is not valid (became a separate statement)
(= (check-position $v $a $b $grid $h $w $valid)
   (match-and &self
     "position is not valid"
     (not (<= 0 $b))
     (== $valid false)))

;; $b is not valid (became a separate statement)
(= (check-position $v $a $b $grid $h $w $valid)
   (match-and &self
     "position is not valid"
     (not (< $b $w))
     (== $valid false)))

;; grid value does not match (became a separate statement)
(= (check-position $v $a $b $grid $h $w $valid)
   (match-and &self
     "position is not valid"
     (tuple-index $grid $a $row)
     (tuple-index $row $b $grid-val)
     (not (== $grid-val $v))
     (== $valid false)))

;; def frontiers(grid: Grid) -> Objects: ;; """ set of frontiers """ ;; h, w = (len(grid), len(grid[0])) ;; row_indices = tuple((i for i, r in enumerate(grid) if len(set(r)) == 1)) ;; column_indices = tuple((j for j, c in enumerate(dmirror(grid)) if len(set(c)) == 1)) ;; hfrontiers = frozenset({frozenset({(grid[i][j], (i, j)) for j in range(w)}) for i in row_indices}) ;; vfrontiers = frozenset({frozenset({(grid[i][j], (i, j)) for i in range(h)}) for j in column_indices}) ;; return hfrontiers | vfrontiers

;; Extracted $row-indices-tuple and $column-indices-tuple into separate statements
;; Extracted $mirrored-grid into a separate statement
;; Extracted $hfrontiers-set and $vfrontiers-set into separate statements

(= (frontiers $grid $output)
   (match-and &self
     "set of frontiers"
     (length $grid $h)
     (tuple-index $grid 0 $first-row)
     (length $first-row $w)
     (match-all &self
       "find row indices with uniform values"
       (range 0 $h 1 $i)
       (tuple-index $grid $i $r)
       (make-set $r $unique-r)
       (length $unique-r 1)
       (collect $i $row-indices))
     (make-tuple $row-indices $row-indices-tuple)) ;; Extracted row-indices-tuple
   (match-and &self
     "set of frontiers"
     (dmirror $grid $mirrored-grid)) ;; Extracted mirrored-grid
   (match-and &self
     "set of frontiers"
     (length $mirrored-grid $mirrored-h)
     (match-all &self
       "find column indices with uniform values"
       (range 0 $mirrored-h 1 $j)
       (tuple-index $mirrored-grid $j $c)
       (make-set $c $unique-c)
       (length $unique-c 1)
       (collect $j $column-indices))
     (make-tuple $column-indices $column-indices-tuple)) ;; Extracted column-indices-tuple
   (match-and &self
     "set of frontiers"
     (match-all &self
       "create horizontal frontiers"
       (range 0 (length $row-indices-tuple) 1 $i)
       (tuple-index $row-indices-tuple $i $row-index)
       (match-all &self
         "iterate over columns"
         (range 0 $w 1 $j)
         (tuple-index $grid $row-index $row)
         (tuple-index $row $j $val)
         (make-tuple ($val (make-tuple ($row-index $j))) $pair)
         (collect $pair $hfrontier))
       (make-frozenset $hfrontier $hfrontier-set)
       (collect $hfrontier-set $hfrontiers))
     (make-frozenset $hfrontiers $hfrontiers-set)) ;; Extracted hfrontiers-set
   (match-and &self
     "set of frontiers"
     (match-all &self
       "create vertical frontiers"
       (range 0 (length $column-indices-tuple) 1 $j)
       (tuple-index $column-indices-tuple $j $column-index)
       (match-all &self
         "iterate over rows"
         (range 0 $h 1 $i)
         (tuple-index $grid $i $row)
         (tuple-index $row $column-index $val)
         (make-tuple ($val (make-tuple ($i $column-index))) $pair)
         (collect $pair $vfrontier))
       (make-frozenset $vfrontier $vfrontier-set)
       (collect $vfrontier-set $vfrontiers))
     (make-frozenset $vfrontiers $vfrontiers-set)) ;; Extracted vfrontiers-set
   (match-and &self
     "set of frontiers"
     (union $hfrontiers-set $vfrontiers-set $output)))

;; def compress(grid: Grid) -> Grid: ;; """ removes frontiers from grid """ ;; ri = tuple((i for i, r in enumerate(grid) if len(set(r)) == 1)) ;; ci = tuple((j for j, c in enumerate(dmirror(grid)) if len(set(c)) == 1)) ;; return tuple((tuple((v for j, v in enumerate(r) if j not in ci)) for i, r in enumerate(grid) if i not in ri))

;; Extracted length of grid into a separate statement
(= (compress $grid $output)
   (match-and &self
     "removes frontiers from grid"
     (length $grid $len)
     ;; Extracted row index with uniform values into a separate statement
     (match-all &self
       "find row indices with uniform values"
       (range 0 $len 1 $i)
       (tuple-index $grid $i $r)
       (make-set $r $unique-values)
       (length $unique-values 1)
       (collect $i $ri)))
   ;; Extracted dmirror of grid into a separate statement
   (dmirror $grid $dm-grid)
   ;; Extracted length of dmirror grid into a separate statement
   (length $dm-grid $dm-len)
   ;; Extracted column index with uniform values into a separate statement
   (match-all &self
     "find column indices with uniform values"
     (range 0 $dm-len 1 $j)
     (tuple-index $dm-grid $j $c)
     (make-set $c $unique-values-c)
     (length $unique-values-c 1)
     (collect $j $ci)))
   ;; Extracted length of grid into a separate statement
   (length $grid $len)
   ;; Extracted construction of new grid without frontiers into a separate statement
   (match-all &self
     "construct new grid without frontiers"
     (range 0 $len 1 $i)
     (tuple-index $grid $i $r)
     (not (member $i $ri))
     (length $r $r-len)
     ;; Extracted construction of new row without frontiers into a separate statement
     (match-all &self
       "construct new row without frontiers"
       (range 0 $r-len 1 $j)
       (tuple-index $r $j $v)
       (not (member $j $ci))
       (collect $v $new-row))
     (make-tuple $new-row $new-r)
     (collect $new-r $new-grid))
   (make-tuple $new-grid $output)))

;; def hperiod(obj: Object) -> Integer: ;; """ horizontal periodicity """ ;; normalized = normalize(obj) ;; w = width(normalized) ;; for p in range(1, w): ;; offsetted = shift(normalized, (0, -p)) ;; pruned = frozenset({(c, (i, j)) for c, (i, j) in offsetted if j >= 0}) ;; if pruned.issubset(normalized): ;; return p ;; return w

;; Extracted $w-1 calculation into a separate statement
(= (hperiod $obj $output)
   (match-and &self
     "horizontal periodicity"
     (normalize $obj $normalized)
     (width $normalized $w)
     (- $w 1 $w-1)
     (match-all &self
       "iterate over possible periods"
       (range 1 $w-1 1 $p)
       (make-tuple (0 (- $p)) $shift-amount) ;; Extracted shift amount into a separate statement
       (shift $normalized $shift-amount $offsetted) ;; Use the extracted variable
       (length $offsetted $len-offsetted)
       (match-all &self
         "prune offsetted set"
         (range 0 $len-offsetted 1 $i)
         (tuple-index $offsetted $i $pair)
         (tuple-index $pair 0 $c)
         (tuple-index $pair 1 $coord)
         (tuple-index $coord 0 $i-coord) ;; Renamed to avoid conflict
         (tuple-index $coord 1 $j)
         (>= $j 0)
         (make-tuple ($c $coord) $pruned-item)
         (collect $pruned-item $pruned-set))
       (make-frozenset $pruned-set $pruned)
       (issubset $pruned $normalized)
       (var $output $p))) ;; $output is set here
   (var $output $w)) ;; $output is set here if no period is found

;; def vperiod(obj: Object) -> Integer: ;; """ vertical periodicity """ ;; normalized = normalize(obj) ;; h = height(normalized) ;; for p in range(1, h): ;; offsetted = shift(normalized, (-p, 0)) ;; pruned = frozenset({(c, (i, j)) for c, (i, j) in offsetted if i >= 0}) ;; if pruned.issubset(normalized): ;; return p ;; return h

;; Extracted normalized height minus one into a separate statement
(= (vperiod $obj $output)
   (match-and &self
     "vertical periodicity"
     (normalize $obj $normalized)
     (height $normalized $h)
     (- $h 1 $h-1)
     ;; Iterate over possible periods
     (match-all &self
       "iterate over possible periods"
       (range 1 $h-1 1 $p)
       (shift $normalized (make-tuple (- $p) 0) $offsetted)
       (length $offsetted $len-offsetted)
       ;; Prune offsetted
       (match-all &self
         "prune offsetted"
         (range 0 $len-offsetted 1 $i)
         (tuple-index $offsetted $i $pair)
         (tuple-index $pair 0 $c)
         (tuple-index $pair 1 $ij)
         (tuple-index $ij 0 $i-val)
         (tuple-index $ij 1 $j)
         (>= $i-val 0)
         (make-tuple ($c $ij) $pruned-pair)
         (collect $pruned-pair $pruned)))
       (issubset $pruned $normalized)
       (var $output $p)))
;; Separate statement for when no period is found
(= (vperiod $obj $output)
   (match-and &self
     "vertical periodicity"
     (normalize $obj $normalized)
     (height $normalized $h)
     (var $output $h)))
⚠️ **GitHub.com Fallback** ⚠️