Haskell Continued traversing an index of an element style in a list

Here is a series of examples I'm trying to do to practice Haskell. I am currently learning about continuing the transfer, but I am a bit confused about how to implement a function such as finding the index of an item in a list that works as follows:

index 3 [1,2,3] id = 2

Examples, such as factorial meaning, since there really was no data processing other than multiplication, but in the case of an index function, I need to compare the element I'm looking at with the element I'm looking for, and I just can't figure out how to do this with a function parameter.

Any help would be great.

+4
source share
2

:

index :: Eq a => a -> [a] -> (Int -> Int) -> Int
index _ [] _  = error "not found"
index x (x':xs) cont
  | x == x'   = cont 0
  | otherwise = index x xs (\ind -> cont $ ind + 1)

:

index :: Eq a => a -> [a] -> (Int -> Int) -> Int
index _ [] _  = error "not found"
index x (x':xs) cont
  | x == x'   = cont 0
  | otherwise = index x xs (cont . (+1))

, - .

, , .

:

λ> index 1 [1,2,3] id
0
λ> index 2 [1,2,3] id
1
λ> index 3 [1,2,3] id
2
λ> index 4 [1,2,3] id
*** Exception: not found

, , - :

useCont a (x:xs) cont = useCont a xs (\valFromXs -> cont $ ??)

, valFromXs ( ), , ( ) , id, Int -> Int. , . useCont xs , xs, .

IMO -

;)

, Haskell.

( ):

index :: Eq a => a -> [a] -> Int -> Int
index _ [] _  = error "not found"
index x (x':xs) ind
  | x == x'    = ind
  | otherwise = index x xs (ind+1)

(. List.elemIndex) Haskells laziness/list-comprehensions, :

index :: Eq a => a -> [a] -> Int
index x xs = head [ i | (x',i) <- zip xs [0..], x'== x ]
+6

a, CPS - (a -> r) -> r r. index :: Eq a => a -> [a] -> Maybe Int, CPS

index :: Eq a => a -> [a] -> (Maybe Int -> r) -> r

index :: Eq a => a -> [a] -> (Int -> r) -> r -> r

.

index x as success failure =

, : . , . -, , as ,

  case as of
    []      -> failure
    (a:as') -> ...

, , x == a. , 0, , , 0 - .

  case as of
    ...
    (a:as') | x == a    -> success 0
            | otherwise -> ...

, , ? , , , , 0 . , . ,

  case as of
    ...
    (a:as') ...
            | otherwise -> index x as' (fun idx -> success (idx + 1)) failure

, "post" ,

-- looking for the value 5, we begin by recursing
1 :
    2 :
        3 :
            4 :
                5 : _ -- match at index 0; push it through the continuation
                0     -- lines from here down live in the continuation
            +1
        +1
    +1
+1

,

            | otherwise -> index x as' (success . (+1)) failure

, , .

index :: Eq a => a -> [a] -> (Int -> r) -> r -> r
index x as success failure
  case as of
    [] -> failure
    (a:as') | x == a    -> success 0
            | otherwise -> index x as' (success . (+1)) failure
+4

All Articles