In particular, I am thinking of a function which involves conditionals changing the recursive behavior and multiple F-algebras.

halting_search :: int -> (a -> bool) -> (a -> a) -> a -> Maybe a
halting_search 0 f_test f_next_candidate candidate = Nothing
halting_search (S n) f_test f_next_candidate candidate = case (f_test candidate) of
  true => Just candidate
  false => halting_search n f_test f_next_candidate (f_next_candidate candidate)

Is this capable of being written just using the cata operator? The reason I'm asking is because I want a functional language that is fairly expressive but not overly expressive, and it seems like one way to do that might be to not allow explicit recursion but make cata a primitive function.


1 Answer 1


Your function is completely structurally recursive on n, so it is pretty much just a change of notation to make it a catamorphism on the natural numbers.

type nat = Z | S of nat 

(* cata : α → (α → α) → nat → α *)                      
let rec cata z s = function
  | Z -> z 
  | S n -> s (cata z s n)

(* halting_search : nat → (α → bool) → (α → α) → α → α option *)             
let halting_search n = 
  cata (fun test next seed -> None)
       (fun recur test next seed -> 
         if test seed then 
           Some seed
           recur test next (next seed))

For languages with higher-order functions and strictly positive datatypes, having a fold is equivalent in expressive power to permitting structural recursion. However, it is not equivalent in terms of efficiency. If you just have fold, then implementing the predecessor function on the Peano natural numbers is O(n), whereas if you have a case form, it is O(1).

(* This is linear time! *)
pred : nat -> nat option 
let pred n = cata None (function 
                           | None   -> Some Z 
                           | Some n -> Some (S n)) n 
  • $\begingroup$ If the language iz lazy, doesn't the predecessor implemented with fold become efficient? $\endgroup$ Commented Feb 14, 2018 at 7:56
  • 1
    $\begingroup$ If you just have the fold as the only eliminator, this is equivalent to the Church encoding in System F, and my understanding is that Church encodings of the natural numbers don't support constant-time predecessor regardless of evaluation order (IIRC, you need the Scott encoding for that). But now I'm wondering if I am wrong... $\endgroup$ Commented Feb 14, 2018 at 13:03
  • $\begingroup$ I am just thinking "what would Haskell do"? $\endgroup$ Commented Feb 14, 2018 at 14:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.