Haskell function to check if an integer appears after another integer

I am writing a function called after, which takes as a parameter a list of integers and two integers. after the list num1 num2 should return True if num1 appears in the list and num2 appears in the afternum1 list. (Not necessarily right after).

after::[Int]->Int->Int->Bool
after [] _ _=False
after [x:xs] b c 
    |x==b && c `elem` xs =True 
    |x/=b && b `elem` xs && b `elem` xs=True

This is what I have so far, my biggest problem is that I do not know how to force num2 to be after num1.

+4
source share
3 answers

There are several different ways to approach this; while the temptation is to go straight to recursion on this, it's nice to avoid using recursion explicitly if there is another option.

. , Haskell, , , . (), :

after :: Int -> Int -> [Int] -> Bool
after a b = elem b . dropWhile (/= a)

, ; , a, , , , b . a, [] , , b, False, .

, , "a" "b" , , . : tail -;)

, :

;

. , , ( ).

data State =
  FindA | FindB | Found
  deriving Eq

"" (aka ) .

after :: Int -> Int -> [Int] -> Bool
after a b xs = foldl go FindA xs == Found
  where
    go FindA x = if x == a then FindB else FindA
    go FindB x = if x == b then Found else FindB
    go Found _ = Found

, :

after :: Int -> Int -> [Int] -> Bool
after _ _ [] = False
after a b (x:xs) 
  | x == a = b `elem` xs
  | otherwise = after a b xs

!

+7

: num1. , num2 .

elemIndex. - elem.

import Data.List (elemIndex)

after xs x y = 
    case x `elemIndex` xs of 
        Just i -> y `elem` (drop (i + 1) xs)
        Nothing -> False
+1

If you want to implement it without elemor elemIndex, you can include a subroutine. Sort of:

after xs b c = go xs False
  where go (x:xs) bFound
          | x == b && not (null xs) = go xs True
          | bFound && x == c        = True
          | null xs                 = False
          | otherwise               = go xs bFound
+1
source

Source: https://habr.com/ru/post/1675468/


All Articles