Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

loops - How to iterate through a list, element by element

I have just started learning Haskell and I am trying to write some basic functions in order to get a better understanding of this language.

I want to write a function which takes a list and an Int (N) as argument and returns the element at index N in the list, without using the !! operator or any built-in function.

Here is what I tried :

myHead :: [a] -> a
myHead (x:_) = x
myHead [] = error "head: empty list"

myNth :: [a] -> Int -> a
myNth x i = if i < 0
  then error "nth: index can't be negative"
  else myNthIterator x i 0

myNthIterator :: [a] -> Int -> Int -> a
myNthIterator [] i n = error "nth: bad index"
myNthIterator (_:x) i n = if i == n
  then myHead x
  else myNthIterator x i ( n + 1 )

It works but it's shifted to the right. For example myNth [1, 2, 3, 4] 2 would give 4 and not 3.

From what I understand, (_:x) removes the first element of the list and I don't see how to iterate through the list element by element.

Could someone put me on the trail? I find it difficult to find resources for beginners in this language.

question from:https://stackoverflow.com/questions/65903835/how-to-iterate-through-a-list-element-by-element

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

We can use Maybe to model whether the index was valid.

nth :: Int -> [a] -> Maybe a
nth 0 (x : _) = Just x
nth n (x : xs) = nth (n - 1) xs
nth _ [] = Nothing

We can pattern match on the index to get our base case, and the list to get the first element and tail.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...