0

I'm iterating through a list of [Char], I'm wondering the best way to perform the iteration.

This function calls itself recursively and passes back to itself a counter that gets decreased per iteration.

Its just for illustrative purposes, so always return True for each Char:

text = ["abcsdsdsdsd"]

exampleFunction :: Int -> String -> [Bool]
exampleFunction textlen text
  | textlen >= 0        = True : exampleFunction (textlen - 1) text
  | otherwise   = []

Using 'textlen' as a counter seems rather imperative, is this the best way and/or the most Haskell-like to implement this?

2
  • Depends on what's your purpose. For example, if you have a list of Ints and want to get the result out of it you can use fold. Or if you want to apply a function to every element of the list you can use map or generalized one that you can apply to Haskell data type such as Maybe, Either, etc. you can use fmap. Take a look at Functor type class. Functor is for those data types that can be mapped over which list is one of the data types. Based on your example you can for example use map _ -> True yourlist Commented Oct 12, 2016 at 11:09
  • 1
    "abcsdsdsdsd" is equivalent to ['a', 'b', 'c', 's', 'd', 's', 'd', 's', 'd', 's', 'd']. Commented Oct 12, 2016 at 11:49

1 Answer 1

2

The counter isn't necessary. The length of the list isn't particularly important; you just use it to determine if the list is non-empty (textlen >= 0) or not. You can do the same thing by pattern matching on the argument itself.

exampleFunction :: [String] -> [Bool]
exampleFunction (x:xs) = True : exampleFunction xs
exampleFunction []  = []

As pointed out in a comment, this particular recursion scheme is abstracted out as the map function:

exampleFunction :: [String] -> [Bool]
exampleFunction xs = map (const True) xs

where const True returns a function that returns True no matter what its argument is. (const True can also be written as an explicit lambda expression (\_ -> True). map applies this function to each element of xs and combines the results into a new list.

Other recursion schemes capture different styles of recursion (filter, foldr, etc), so while it is always possible to write an explicit recursive function to accomplish your task, you can often avoid it by using the appropriate higher order function.


I'm abusing the term recursion scheme a bit; map and filter can be thought of as special cases of foldr, which is an example of a general recursion scheme known as a catamorphism.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.