Home > Software design >  Haskell Higher order filter function for a list
Haskell Higher order filter function for a list

Time:11-13

I am trying to use a higher order filter function to pass this log of values

test log = 
[
('B', 100, 1104, "VTI", 1),
('B', 200, 36, "ONEQ", 3),
('B', 50, 1223, "VTI", 5),
('S', 150, 1240, "VTI", 9),
('B', 100, 229, "IWRD", 10),
('S', 200, 32, "ONEQ", 11),
('S', 100, 210, "IWRD", 12)
]

These datatypes are: Char, Int,Int, String, Int

I Would like to be able to write a function like this:

get_trades "VTI" test_log

Which will provide this output:

[('B',100,1104,"VTI",1),('B',50,1223,"VTI",5),('S',150,1240,"VTI",9)]

I am trying to filter it on the String datatype where all I can understand currently in what I can use is the map function.

I have tried this:

get_trades (action, units, price, stocks, day) = 

    let filter_stocks | show stocks == map  x
                      | otherwise     = "Incorrect, a correct stock "
    in
       get_trades

I feel like I am overcomplicating this as I am not sure how the filter function could be used for this. Any guidance would be great :)

CodePudding user response:

You can define the function you got your previous question (given a string and a trade, return whether the trade has the string) and then use it in filter:

type Trade = (Char, Int, Int, String, Int)

test_log :: [Trade]
test_log = [
  ('B', 100, 1104, "VTI", 1),
  ('B', 200, 36, "ONEQ", 3),
  ('B', 50, 1223, "VTI", 5),
  ('S', 150, 1240, "VTI", 9),
  ('B', 100, 229, "IWRD", 10),
  ('S', 200, 32, "ONEQ", 11),
  ('S', 100, 210, "IWRD", 12)
  ]

check_stock :: String -> Trade -> Bool
check_stock x (_, _, _, y, _) = x == y

get_trades :: String -> [Trade] -> [Trade]
get_trades symbol = filter (check_stock symbol)

main = print $ get_trades "VTI" test_log
-- [('B',100,1104,"VTI",1),('B',50,1223,"VTI",5),('S',150,1240,"VTI",9)]
  • Related