Message Boards Message Boards

1
|
4344 Views
|
2 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Idiom to recurse over a list ?

Posted 8 years ago

In functional languages, such as Haskell, where list is a recursive datatype of the form List[x] -> EmptyList[x] | x:List[x], structural induction over a list may be expressed with pattern matching like so :

foldr f z []     = z 
foldr f z (x:xs) = f x (foldr f z xs)

But in the Wolfram Language, though the First and Rest functions are available on lists, as I understand it, List is not a recursively organized structure, but rather a flat array of substructures (probably with O(1) access time at a random position in the list).

How then does one go about writing the analogue of the Haskell foldr HOF ? Mimicking structural induction over recursively defined Lists, one could go like this :

2 ways of writing foldr

But is there some more idiomatic or preferred, or more efficient way of doing this ?

Thanks a lot for your help.

Just as an aside, using a right associative operator for f visually makes plain the difference between foldr and Fold :

Fold with a right associative operator

POSTED BY: Fabien Todescato
2 Replies

Is that ok?

 Fold[#2 -> #1 &, 0, Reverse @ Range @ 8]
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 0
POSTED BY: Kuba Podkalicki

Thanks Kuba, reversing the arguments of the function and folding over the reversed list does indeed do the trick.

Appreciated your help.

POSTED BY: Fabien Todescato
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract