Skip to content

Instantly share code, notes, and snippets.

@WillNess
Created May 20, 2013 05:44
Show Gist options
  • Select an option

  • Save WillNess/5610590 to your computer and use it in GitHub Desktop.

Select an option

Save WillNess/5610590 to your computer and use it in GitHub Desktop.
it's kind of a [paramorphism][2]. Encoded via `foldr + tails`,
import Data.List (tails)
foo :: (a -> b -> b) -> (a -> b) -> [a] -> b
foo g k = foldr (\xs r -> case xs of [x] -> k x; (x:_) -> g x r) undefined
. init . tails
Richard Bird in his 2010 book "Pearls of Functional Algorithm Design" gives it a
special name, [`foldrn`][1], with a direct implementation which follows the usual
`foldr` implementation very closely. (I'm not copying it here because it's part of
a copyrighted book).
[1]: http://books.google.co.il/books?id=ZQJnYoAmw6gC&pg=PA42&lpg=PA42&dq=foldrn&source=bl&ots=7zcGAESrzM&sig=OFQVpR_-M4mOmKYnOBUXfEB4xAo&hl=en&sa=X&ei=A3aYUbKVDsLQOaqjgIAP&redir_esc=y#v=onepage&q=foldrn&f=false
[2]: http://stackoverflow.com/questions/13317242/what-are-paramorphisms/13317563#13317563
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment