简体   繁体   中英

Interleaving function definitions in Haskell

I'm writing a couple pattern-matching functions that recurse on each other, and I would like to be able to interleave their definitions like

recA [pattern ...] = [.. something that might call recB with the next pattern ..]
recB [pattern ...] = ...
recA [other ...]   = ...
...b

etc. Is this possible? Is there some more idiomatic alternative?

The Haskell 2010 report, section 4.4.3.1 Function Bindings says that

Note that all clauses defining a function must be contiguous, and the number of patterns in each clause must be the same.

So you can't interleave recA and recB as in your example.

There's no theoretical reason (that I can see) why the compiler shouldn't be able to group the various clauses together; I suspect this rule was introduced to guard against human error and confusion. As a silly example, what's wrong with the following?

function1 [] = "a"
functionl (x:xs) = "b"
function1 (x:y:xs) = "c"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM