Home > Software engineering >  How to do if statements inside main method in haskell?
How to do if statements inside main method in haskell?

Time:11-08

I'm new to haskell and am trying to solve a fairly simple problem on hte surface but has proven to be really difficult. I have this program where I want to have a target sum for example 10 and then given an array I want to find the pairs in that array that add to the target sum. Heres what I have:

findPairs :: [Int] -> [Int] -> ([[Int]], Int )
findPairs x y = do
  if x   y == 10
    then 
        let thePairs = zip x y


main = do
  a <- [1, 8, 5, 2, 5, 6, 7, 3, 9, 4]
  b <- [1, 8, 5, 2, 5, 6, 7, 3, 9, 4]
  findPairs a b

I keep getting the same error: parse error (possibly incorrect indentation or mismatched brackets). So given the array [1, 8, 5, 2, 5, 6, 7, 3, 9, 4], if my target sum is 10 for example, my program will return [(1,9),(8,2),(5,5),(7,3),(6,4)]. Any advice would be greatly appreciated!

CodePudding user response:

If your findPairs function is to be able to return [(1,9),(8,2),(5,5),(7,3),(6,4)], its return type must be [(Int,Int)] and not ([[Int]], Int).

The system does not extract items from their respective lists automatically. You have to do it manually. Besides, it is customary to note the item list as xs and the item as x for clarity.

You can write the function like this, for example:

findPairs :: [Int] -> [Int] -> [(Int,Int)]
findPairs xs ys =
  do
    -- we are in a do construct within the list monad
    x <- xs
    y <- ys
    if (x   y == 10)  then  [(x,y)]  else  []

In a list monadic context, function return just wraps 42 into [42], so you do not necessarily need to use return every time.

Sample main program:

main :: IO ()
main = do
  -- we are in a do construct within the IO monad
  let as    = [1, 8, 5, 2, 5, 6, 7, 3, 9, 4]
  let bs    = [1, 8, 5, 2, 5, 6, 7, 3, 9, 4]
  let pairs = findPairs as bs
  let msg   = "pairs = "      (show pairs)
  putStrLn msg

Program output:

pairs = [(1,9),(8,2),(5,5),(5,5),(2,8),(5,5),(5,5),(6,4),(7,3),(3,7),(9,1),(4,6)]
  • Related