haskell,recursion , Recursion scheme in Haskell for repeatedly breaking datatypes into “head” and “tail” and yielding a structure of results

## Question:

In Haskell, I recently found the following function useful:

``````listCase :: (a -> [a] -> b) -> [a] -> [b]
listCase f [] = []
listCase f (x:xs) = f x xs : listCase f xs
``````

I used it to generate sliding windows of size 3 from a list, like this:

``````*Main> listCase (\_ -> take 3) [1..5]
[[2,3,4],[3,4,5],[4,5],[5],[]]
``````

Is there a more general recursion scheme which captures this pattern? More specifically, that allows you to generate a some structure of results by repeatedly breaking data into a "head" and "tail"?

This looks like a special case of a (jargon here but it can help with googling) paramorphism, a generalisation of primitive recursion to all initial algebras.

## Reimplementing ListCase

Let's have a look at how to reimplement your function using such a combinator. First we define the notion of paramorphism: a recursion principle where not only the result of the recursive call is available but also the entire substructure this call was performed on:

The type of `paraList` tells me that in the `(:)` case, I will have access to the head, the tail and the value of the recursive call on the tail and that I need to provide a value for the base case.

``````module ListCase where

paraList :: (a -> [a] -> b -> b) -- cons
-> b                 -- nil
-> [a] -> b          -- resulting function on lists
paraList c n []       = n
paraList c n (x : xs) = c x xs \$ paraList c n xs
``````

We can now give an alternative definition of `listCase`:

``````listCase' :: (a -> [a] -> b) -> [a] -> [b]
listCase' c = paraList (\ x xs tl -> c x xs : tl) []
``````

## Considering the general case

In the general case, we are interested in building a definition of paramorphism for all data structures defined as the fixpoint of a (strictly positive) functor. We use the traditional fixpoint operator:

``````newtype Fix f = Fix { unFix :: f (Fix f) }
``````

This builds an inductive structure layer by layer. The layers have an `f` shape which maybe better grasped by recalling the definition of `List` using this formalism. A layer is either `Nothing` (we're done!) or `Just (head, tail)`:

``````newtype ListF a as = ListF { unListF :: Maybe (a, as) }
type List a = Fix (ListF a)

nil :: List a
nil = Fix \$ ListF \$ Nothing

cons :: a -> List a -> List a
cons = curry \$ Fix . ListF .Just
``````

Now that we have this general framework, we can define para generically for all `Fix f` where `f` is a functor:

``````para :: Functor f => (f (Fix f, b) -> b) -> Fix f -> b
para alg = alg . fmap (\ rec -> (rec, para alg rec)) . unFix
``````

Of course, `ListF a` is a functor. Meaning we could use `para` to reimplement `paraList` and `listCase`.

``````instance Functor (ListF a) where fmap f = ListF . fmap (fmap f) . unListF

paraList' :: (a -> List a -> b -> b) -> b -> List a -> b
paraList' c n = para \$ maybe n (\ (a, (as, b)) -> c a as b) . unListF

listCase'' :: (a -> List a -> b) -> List a -> List b
listCase'' c = paraList' (\ x xs tl -> cons (c x xs) tl) nil
``````

You can implement a simple bijection `toList`, `fromList` to test it if you want. I could not be bothered to reimplement `take` so it's pretty ugly:

``````toList :: [a] -> List a
toList = foldr cons nil

fromList :: List a -> [a]
fromList = paraList' (\ x _ tl -> x : tl) []

*ListCase> fmap fromList . fromList . listCase'' (\ _ as -> toList \$ take 3 \$ fromList as). toList \$ [1..5]
[[2,3,4],[3,4,5],[4,5],[5],[]]
``````

# Related:

## BAD_ACCESS during recursive calls in Swift

swift,recursion
While toying with Swift, I've encountered a situation which crashes and I still not have figured out why. Let define: class TestClass { var iteration: Int = 0 func tick() -> Void{ if iteration > 100000 { print("Done!") return } iteration++ tick() } } The tick() function calls itself and...

## Haskell: When declaring a class, how can I use a type variable that is not immediately in the constructors?

I want to define a function, <-? to check whether an element is in a list/set/map. module Test where import qualified Data.Map as Map import qualified Data.Set as Set class Memberable a where (<-?) :: b -> a -> Bool instance Memberable [x] where (<-?) = elem instance Memberable (Map.Map...

## BSTD inorder traversal produces erroneous behaviour

java,debugging,recursion,immutability
I have a BSTD implementation which is inserting values incorrectly and I can't find for the life of me what is going on. EXPECTED ACTUAL -------- ---------- Alex Janice Carlos Janice Elton Janice Janice Zidane Zidane Zidane Implementation private Node<K,E> insert(Node<K,E> node, K key, E elem) { if (node ==...

## apply a transformation with function inline

Starting from a simple case of "fold" (I used (+) but can be anything else): Prelude.foldl (+) 0 [10,20,30] is it possible apply an inline transformation similar to (that doesn't work): Prelude.foldl ((+) . (\x -> read x :: Int)) 0 ["10","20","30"] In case not, is there an alternative to...

## Best practice for handling data types from 3rd party libraries in Haskell?

I'm just getting into my first real Haskell project of size (a web app), and I'm starting to run into issues with types from 3rd party libraries leaking all over my code. Here is a quick example: My Parser module imports Test.Parsec, and the exports a function (parseConfig) that returns...

## How can I declare a counter inside of my recursive function? (Additive Persistence: Coderbyte)

javascript,algorithm,recursion
While working through some Coderbyte challenges, I was able to solve the following problem recursively, but was hoping to get some feedback on how I can improve it. Have the function AdditivePersistence(num) take the num parameter being passed which will always be a positive integer and return its additive persistence...

## Python recursive function not recursing

python,recursion
I'm trying to solve a puzzle, which is to reverse engineer this code, to get a list of possible passwords, and from those there should be one that 'stands out', and should work function checkPass(password) { var total = 0; var charlist = "abcdefghijklmnopqrstuvwxyz"; for (var i = 0; i...

## Python RuntimeError: maximum recursion depth exceeded in cmp

python,list,dictionary,recursion
I have a complex data structure that I'm trying to process. Explanation of the data structure: I have a dictionary of classes. The key is a name. The value is a class reference. The class contains two lists of dictionaries. Here's a simple example of my data structure: import scipy.stats...

I'm using a graphic library in Haskell called ThreePennyUI. In this library the main function returns a UI monad object. This causes me much headache as when I attempt to unpack IO values into local variables I receive errors complaining of different monad types. Here's an example of my problem:...

## First three items of a list in Haskell

I am very new to Haskell, and struggling a bit with a function here. The premise is simple enough: Run through a list, and combine each 3 items next to each other with another function and return a list with the results. The problem is to do it in a...

## Identifying methods that can be converted into a recursive method

java,recursion
I've been searching around to practice my recursion, however I've run out of practice problems on codingBat, and a few others. If you've got more suggestions, feel free to comment them! My question is how do YOU identify when a method can simply be turned into a recursive method, even...

## 3 X 3 magic square recursively

c++,algorithm,math,recursion
I'm trying to find all possible solutions to the 3X3 magic square. There should be exactly 8 solutions. My code gets them all but there are a lot of repeats. I'm having a hard time tracking the recursive steps to see why I'm getting all the repeats. // This program...

## sum of Digits through Recursion

java,function,recursion,sum,digit
I am trying to make a recursive function which should return the sum of digits. The function should have only one argument. So far I have this; public int sumDigits(int n) { if(n%10 == n) // last digit remains return n; else{ int rightdigit; rightdigit = n%10; // taking out...

## Eloquent Javascript: DOM Animation snippet

javascript,animation,dom,recursion,requestanimationframe
I'm trying to understand everything that is happening in this little code example in Eloquent Javascript: The Document Object Model (Chapter 13), but I'm not clear on where exactly the value for "time" is being passed into the animate() function before the function itself gets passed into requestAnimationFrame(). What exactly...

## Decremented value called in the recursion in Haskell

So, I have this function that aligns the text to the left for a given column width. I have already fixed some of its problems, but I am unable to make it not use the decremented parameter once it is called, but to return to the starting value of n....

## Recursive solution doesn't iterate correctly

ruby,algorithm,search,recursion
I'm working through a toy problem in Ruby: how to produce all possible 10-digit phone numbers where each successive number is adjacent to the last on the keypad. I've represented the adjacent relationships between numbers, and have a recursive function, but my method isn't iterating through the whole solution space....

## Recurions: simple spiral with python turtle

python,recursion,turtle-graphics
I'm trying to recreate a function spiral() using recursion that takes the parameters initLen (pixel length of first side), N (angle connecting segments), and mult (a float amount indicating how much bigger/smaller each segment should be after each turn - ex: mult = 0.5 means each segment would be half...

## Recursive function returns undefined when there is only one numerical possibility

javascript,recursion
The code below contains a recursive method which should always return 7 however it return undefined whenever it has to re-generate a number because the number generated was already contained within the array that is defined at the top of the code. My question is... why is this happening and...

## Keep track of loop without a counter

Say, I got a list which length can be odd or even. Every iteration , I remove two items from the list. If there is one or no item at the end, I end the execution. If I store (length list)/2 every loop, I will get e.g. [5,4,3...] for a...

## Scala first program issue

scala,recursion,case,frequency
I have just started to learn Scala after some experience with functional programming in other languages. def freq(c:Char, y:String, list:List[(Char,Int)]): List[(Char,Int)] = list match{ case _ => freq(c, y.filter(_ == c), list :: List((count(c,y),c))) case nil => list } In the above code I am getting an error when trying...

## Recursive algorithm that returns a bool when checking if array[i] == i (must be O(log n))

c++,arrays,algorithm,recursion
I'm trying to write a recursive algorithm that returns true if at least one array[i] == i. And false if there is no array[i] = i. Also, the parameters needed are (int * arr, int start, int end). So i'll be traversing the array with a pointer. For example: int...

## T-SQL Ordering a Recursive Query - Parent/Child Structure

sql,tsql,recursion,order,hierarchy
I am trying (and failing) to correctly order my recursive CTE. My table consists of a parent-child structure where one task can relate to another on a variety of different levels. For example I could create a task (this is the parent), then create a sub-task from this and then...

## R: recursive function to give groups of consecutive numbers

r,if-statement,recursion,vector,integer
Given a sorted vector x: x <- c(1,2,4,6,7,10,11,12,15) I am trying to write a small function that will yield a similar sized vector y giving the last consecutive integer in order to group consecutive numbers. In my case it is (defining groups 2, 4, 7, 12 and 15): > y...

## Haskell - generate and use the same random list

In Haskell, I'd like to generate a random list of Ints and use it throughout my program. My current solution causes the array to be created randomly each time I access/use it. How can I overcome this problem?...

When given an array of integers, I'm trying to change each element with the product of the integers before it. For example, int[] array = {2,2,3,4}; is now: {2, 4, 12, 48}; I added each element to a LinkedList, and I'm trying to do this recursively. This is what I...

## My function will log a value to the console, but it won't return the same value - why? [duplicate]

javascript,arrays,function,recursion
This question already has an answer here: Return value of recursive function is 'undefined' 1 answer I've created the following function to flatten a nested array: function steamroller(arr) { arr = arr.reduce(function(a, b, i){ return a.concat(b); },[]); if (!Array.isArray(arr[arr.length-1])) {console.log(arr); return arr;} steamroller(arr); } steamroller([1, [2], [3, [[4]]]]); The...

## algorithm to get all combinations of splitting up N items into K bins

algorithm,recursion,permutation
Assuming I have a list of elements [1,2,3,4,] and a number of bins (let's assume 2 bins), I want to come up with a list of all combinations of splitting up items 1-4 into the 2 bins. Solution should look something like this [{{1}, {2,3,4}}, {{2}, {1,3,4}}, {{3}, {1,2,4}}, {{4},...

## Too much recursion - jquery - autocomplete

javascript,jquery,recursion,jquery-ui-autocomplete
So here is my autocomplete functionality: var selected; var itemAdded = false; \$('.js-main-search').autocomplete({ minLength: 3, source: function(request, response) { \$.getJSON('/dashboard/searchDocumentsAndCompanies.do', { q: request.term}, function(data) { if(data.length == 0){ data = [ {name: 'No matches found', resultType: 'COMPANY', noResults: true}, {name: 'No matches found', resultType: 'BRANCHES', noResults: true}, ]; } data.unshift({name:...

## Get each fibbonacci value in haskell

I'm learning haskell and I have the following code: fib a b = a : fib b (a + b) findFibSum = sum [x | x <- fib 1 2, mod x 2 == 0 && x < 100] If I run findFibSum nothing happens, it just sits there. Shouldn't...

## How do I avoid writing this type of Haskell boilerplate code

I run into this situation often enough for it to be annoying. Let's say I have a sum type which can hold an instance of x or a bunch of other things unrelated to x - data Foo x = X x | Y Int | Z String | ...(other...

## R: split string into numeric and return the mean as a new column in a data frame

r,recursion,dplyr,strsplit
I have a large data frame with columns that are a character string of numbers such as "1, 2, 3, 4". I wish to add a new column that is the average of these numbers. I have set up the following example: set.seed(2015) library(dplyr) a<-c("1, 2, 3, 4", "2, 4,...

## How can I express foldr in terms of foldMap for type-aligned sequences?

I'm playing around with type-aligned sequences, and in particular I'm messing around with the idea of folding them. A foldable type-aligned sequence looks something like this: class FoldableTA fm where foldMapTA :: Category h => (forall b c . a b c -> h b c) -> fm a b...

## Stopping condition on a recursive function - Haskell

So, I have this function which aims to align the text on the left without cutting words(only white spaces). However my problem is that I cannot find a stopping condition of the function and it goes infinitely. f n "" = "" --weak condition f n s = if n...

## Replace all [ ] with {} - as short as possible [on hold]

Given the code below: import Data.List; main = (readLn :: IO [Integer]) >>= print . subsequences It takes a list of integers from standard input (for example [1,2,3]) and outputs something like: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] I want it to be like this: {},{1},{2},{1,2},{3},{1,3},{2,3},{1,2,3}} so my goal is to replace every [ and...

## Reversing an integer using recursive method in C++

c++,recursion
I have this recursive function to reverse a positive integer. Anybody having an efficient algorithm to do the task using fewer recursive calls (but still using recursion), please post here! int countDigit (const int & _X) { if (_X < 10) return 1; return (countDigit(_X / 10) + 1); }...

## Recusively count children nodes in binary tree

java,recursion,binary-tree,nodes
So my coding exercise is given the reference to the node count its children. I've decided to use recursion and I was wondering is this a elegant way to do this: Let's assume there is class Node which represent every node in the tree: public Node { int data: Node...

## Reverse Linked List recursively, why it is wrong

recursion
Problem: Reverse a singly linked list recursively. I know how to solve this problem, but one of my recursive methods is wrong, I can not figure out what's wrong with this code. Could anyone figure out that? Thanks a lot! Test case: Input: [1,2,3] Output: [3,1] Expected: [3,2,1] public class...

## How to “wrap” monadic return value

I have the following code: data APNSIdentifier = NoIdentifier | Identifier Word32 deriving (Show, Eq) newtype APNSItem = Item Put createNotificationIdentifierItem :: APNSIdentifier -> APNSItem <--- here createNotificationIdentifierItem (Identifier identifier) = do putWord8 3 putWord16be 4 putWord32be identifier How can I "wrap" the Put monad with an APNSItem? Do I...

## How does ((a++,b)) work? [duplicate]

c,function,recursion,comma
This question already has an answer here: What does the comma operator `,` do in C? 8 answers In the below block of code, I am trying to understand how the line return reverse((i++, i)) is working. #include <stdio.h> void reverse(int i); int main() { reverse(1); } void reverse(int...

## Haskell return lazy string from file IO

Here I'm back again with a (for me) really strange behaviour of my newest masterpiece... This code should read a file, but it doesn't: readCsvContents :: String -> IO ( String ) readCsvContents fileName = do withFile fileName ReadMode (\handle -> do contents <- hGetContents handle return contents ) main...

## EXC_BAD_ACCESS error occurring when running recursive merge sort method in a thread

I'm having trouble with my C++ code in xCode. I've tried debugging and I can't fix it. I know it's roughly when my mergeSort() method calls my mergeNumbers() method. I know it's not the method itself because I've run the method without threading and it works just fine. It's when...

## Combining Event and an attribute in threepenny-gui

I have an Event String which I want to sink into a textarea. This works fine, but now I want to combine the current value of a checkbox selection to this string. First I did this by using checkedChange of the checkbox which works, but has a problem. If the...

## How to flatten a structure of embedded Set and Hash

ruby,recursion
I would like to convert an embedding structure into a flat one. An embedding structure is a set of 0 or more objects, such as: a string or a hash having some string as key and some other embedding structure as value. A flat structure is a set of arrays...

## How does Frege generalize number literals?

It appears that Frege can evaluate 1/2 to return the Double value 0.5. The literal 1 is of type Int. It seems to be promoted to Double, which is a type in the Real class and thus knows the / operator. How does this happen? Is it using the Haskell...

## Implementing map on a tree using fold

I am trying to implement a map using fold. I could do so in Haskell data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show) foldTree :: Tree a -> b -> (b -> a -> b -> b) -> b foldTree EmptyTree d _ =...

## Recursive Lag Column Calculation in SQL

sql,sql-server,recursion
I am trying to write a procedure that inserts calculated table data into another table. The problem I have is that I need each row's calculated column to be influenced by the result of the previous row's calculated column. I tried to lag the calculation itself but this does not...