Home > Software engineering >  Haskell: how to properly see if a value is or is not in a list
Haskell: how to properly see if a value is or is not in a list

Time:10-23

Working on some practice haskell and I am making a search function in my program. I am not getting the desired output and I think I know why and that is it is only checking the head of the list and not the tail or (xs). Here is what I tried..

searchtask [] searchkey = do
  putStrLn ""
searchtask (x : xs) searchkey = do
  if x == searchkey
    then putStrLn $  " Found task: "    x
      else if x /= searchkey then putStrLn $ "Could not find task."    search key

    else searchtask xs searchkey

Do I have to iterate through the list?

CodePudding user response:

First, there's no need to check x /= searchkey. If x == searchkey is false, you know that x /= searchkey will be true. Second, since it can never be false, then your recursive call is never made. Finally, you don't want to print "Could not find task" until you've checked every value in the list.

searchtask [] searchkey = putStrLn $ "Could not find task "    searchkey
searchtask (x:xs) searchkey = do
   if x == searchkey
   then putStrLn $ " Found task: "    x
   else searchtask xs searchkey
  • Related