2

So I've been doing this program which receives a function f, a number a and a list b and it should return a list [a, f(a,b), f(f(a,b),b, ..] iterating through the list b and using recursion. Do you guys know how I can optimize my code?

calculate :: (a -> b -> a) -> a -> [b] -> [a]
help :: (a -> b -> a) -> a -> [b] -> [a]

help f a (x:xs) = (f a x) : (calculate f (f a x) xs)
help f a [] = []

calculate f a b = a : (help f a b)
9
  • 1
    What about scanl f a (repeat b)? Commented Jan 16, 2019 at 20:02
  • 4
    Hint: doit f (x:xs) = x : do_the_full_recursive_step f xs Commented Jan 16, 2019 at 20:04
  • 3
    "Do you guys know how to optimise my code?" What do you mean by "optimise"? Have you timed its performance? What are you asking? Commented Jan 16, 2019 at 20:17
  • Thank you. @AJFarmar no, I meant a way of shortening it. Commented Jan 16, 2019 at 20:18
  • 1
    Are you sure this code does what you want it to do? Commented Jan 17, 2019 at 1:54

1 Answer 1

2

calculate f a b = tail . concatMap (replicate 2) . scanl f a $ b.

The replicate bit is probably in error. If so, then simply calculate = scanl.

This translates the code, as the "[a, f(a,b), f(f(a,b),b, ..]" from the text contradicts it (and it contradicts the text itself, which talks of "iterating through the list b").

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

2 Comments

This works perfectly fine if i use it as calculate f a b = tail . concatMap (replicate 1) . scanl f a $ b
OK, but concatMap (replicate 1) is the same as id and id . f is the same as simply f itself. And with replicate 1 you don't need the tail either.

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.