John Smith
John Smith

Reputation: 99

Make a static variable during recursion in Haskell

I have this code:

filtro :: [(String, Int, Int)] -> [(String, Int, Int)]
filtro [] = [] 
filtro (x:xs) 
    | pior x xs = filtro xs
    | otherwise = x : filtro xs

I need to make this variable static: pior x xs filtro xs . Any idea how?

Upvotes: 0

Views: 247

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70317

It sounds like you want to apply pior to x and the whole list, not just the tail. I think some degree of separation of concerns could do you some favors. First off, your function is just filter, which can be defined as

filter :: (a -> Bool) -> [a] -> [a]
filter _ [] = []
filter p (x:xs)
  | p x = x : filter x xs
  | otherwise = filter x xs

So we can use that to our advantage. Then

filtro :: [(String, Int, Int)] -> [(String, Int, Int)]
filtro xs = filter (\x -> not (pior x xs)) xs

Since we make a closure around xs when it's the whole list, it'll remain the whole list in that closure for all of time (remember, in Haskell, variables don't change, ever).

If you really want to do it as one recursive function, you'll need an extra argument which remains the whole list for the duration of the computation.

filtro' :: [(String, Int, Int)] -> [(String, Int, Int)] -> [(String, Int, Int)]
filtro' _ [] = [] 
filtro' xss (x:xs) 
    | pior x xss = filtro xss xs
    | otherwise = x : filtro xss xs

filtro :: [(String, Int, Int)] -> [(String, Int, Int)]
filtro xs = filtro' xs xs

In either case, you'll need to store the whole list somewhere, whether it's in an extra parameter or (preferred) transparently in a closure.

Upvotes: 4

Related Questions