简体   繁体   中英

Is a function that calls itself only once no matter the input recursive?

Consider a function that does an operation and calls itself at most once (not more than one “recursion” level) no matter what the input is. Is this function considered recursive?

Example:

join1 :: [Maybe a] -> [a]
join1 [Just x] = [x]
join1 [Nothing] = []
join1 (x) = concat (map join1 (map (\k->[k]) x))

In this case, when calling: Join1 [nothing, just 2, just 3,...] The join1 function will be called on each element, entering immediately the termination condition

Yes, it is recursive. The number of calls at runtime and the runtime recursion depth is irrelevant. A definition x = expression is said to be recursive if x appears in expression , referring to the x we are defining right now.

Briefly put, "recursiveness" is a syntactic property of the definition, and does not consider the runtime behavior.

As a silly example, this definition is recursive, even if it never calls itself at runtime. Even if it could trivially simplified into a non-recursive one.

identity :: a -> a
identity x = (\_ -> x) identity

You have underestimated the valid inputs for your function. What if you call it like:

join1 [Nothing, Just [Just 2, Nothing, Just 3], Just [Nothing, Just 4]]

Or going the other way, what if you call it like:

join1 [Nothing]

Non-infinite recursive function calls are always limited in depth. Calling itself once or even zero times for any specific input is perfectly valid. In fact, it won't terminate if you don't allow input with zero recursive calls.

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