How can I do a function (recursivily) that substitute the argument b(1) for an argument a(0) on a list?
For example:
substitute 0 1 [1,0,3,0,4,0,0]
[1,1,3,1,4,1,1]
Thanks.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The simplest is to use list comprehension:
subst a b xs = [c | x<-xs, let c=if x==a then b else x].But that’s no recursion. With recursion, it is just a case analysis for list structure (i.e. structural recursion):
which is an instance of the
foldr(ormap) pattern:It is usually advisable to use a “worker” function in recursive definitions, like so:
but if you stare at it for a moment you recognize that it is follows the
mappattern. In Haskell recursive patterns are captured by higher-order functions, likemap,filteretc.