I'm getting used to Haskell's higher-order functions. Usually I can replace explicit patterns of recursion with functions like map, fold, and scan. However, I often run into the following recursion pattern which I don't understand how to express using higher-order functions:
f (x:[]) = k x
f (x:xs) = g x (f xs)
For instance, suppose I am representing analytic tableaux. Then I create a data type such as:
data Tableau = N Expr | S Expr (Tableau) | B Expr (Tableau) (Tableau)
If I want to convert a list of Expr
s into a tableau structure, I want a function part of which might resemble:
f (x:[]) = N x
f (x:xs) = S x (f xs)
Now, I see three options: (1) create a function which decides, given a tableau and a list, whether the next branch in the tableau should be an S
or N
(or B
, but we'll ignore that case); (2) use a higher-order function to encapsulate the recursion pattern of f
; (3) use a function like f
.
What would the best option be?