0

In Haskell, I'm trying to solve a problem where I need to have a function that receives a list of integers and returns the biggest product of two adjacent numbers.

Example: f [5,6,1,3,9] would return 30, that is the product of 5 and 6

The function type would be something like this:

f :: [Int] -> Int

I thought to solve that using recursion to iterate the list getting the 2 head elements with a pattern like this: (x1:x2:xs) The problem is that I don't know how to keep the product value to compare if the current product is bigger than the last product.

Any ideas?

3
  • What if one gives the empty list? Or a list with one element? Commented Oct 24, 2017 at 22:04
  • 2
    Can you think of a way to create a list with every pair of adjacent numbers, f [5, 6, 1, 3, 9] == [(5, 6), (6, 1), (1, 3), (3, 9)]? Commented Oct 24, 2017 at 22:06
  • Another possibility would be to make a recursive helper function go, that has an additional argument used as intermediate result (your current maximum). The problem: you have to find an initial value. Therefore consider changing the return type of your function and of the intermediate result to an Maybe Int. Commented Oct 24, 2017 at 22:12

1 Answer 1

5

Since Haskell lists are lazy, you can solve this problem using a list-based approach instead of explicitly holding onto a maximum without losing efficiency. Starting with the original list:

> let f x = x
> f [5,6,1,3,9]
[5,6,1,3,9]

get a list of pairs by zipping the entire list with a left-shifted list:

> let f x = zip x (tail x)
> f [5,6,1,3,9]
[(5,6),(6,1),(1,3),(3,9)]

use the related function zipWith to get products instead of pairs:

> let f x = zipWith (*) x (tail x)
> f [5,6,1,3,9]
[30,6,3,27]

and get the maximum from that list:

> let f x = maximum (zipWith (*) x (tail x))
> f [5,6,1,3,9]
30
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.