差距函数,它使用foldl或foldr返回列表中两个元素的首次出现之间的整数距离.(Haskell) [英] Gap function that returns the integer distance between first appearance of two elements in a list using either foldl or foldr.(Haskell)
问题描述
类型定义如下: 间隙::(Eq a)=> a-> a-> [a]-> Maybe Int 我已经在这个问题上停留了一个多小时,并且不知道如何解决该问题.我知道它需要使用fold并熟悉该主题. 请考虑必须使用foldl或foldr. 调用时,输出应如下所示
the type is defined as follows: gap :: (Eq a) => a -> a -> [a] -> Maybe Int I have been stuck on this problem for more than an hour and have no idea how to approach the problem. I am aware that it requires the use of fold and am familiar with that topic. Please take into consideration that either foldl or foldr must be used. The output when called ought to look like this
间隙3 8 [1..10] =只需5
gap 3 8 [1..10] =Just 5
间隙8 3 [1..10] =无
gap 8 3 [1..10] =Nothing
gap'h''l'"hello" =只需2
gap 'h' 'l' "hello" =Just 2
gap'h''z'"hello" =无
gap 'h' 'z' "hello" =Nothing
推荐答案
您可以dropWhile
列表,直到找到起始元素,然后从右侧折叠,从Nothing
开始,一次替换为Just 1
您按下了end元素,并fmap
ing +1
到累加器.在代码中:
You might dropWhile
the list until you find the starting element and then fold from the right, starting with Nothing
, replacing that with Just 1
once you hit the end element, and fmap
ing +1
to the accumulator. In code:
gap :: Eq a => a -> a -> [a] -> Maybe Int
gap from to xs = case dropWhile (/= from) xs of
[] -> Nothing
(_:rest) -> gap' to rest
gap' :: Eq a => a -> [a] -> Maybe Int
gap' to = foldr f Nothing
where f x acc | x == to = Just 1
| otherwise = (+1) <$> acc
令人高兴的是,如果序列中元素多次出现,它将正常工作:
The nice thing is that it works correctly if you have several occurences of the elements in your sequence:
*Main> gap 3 8 $ [1..10] ++ [1..10]
Just 5
*Main> gap 3 8 [1, 2, 3, 3, 3, 8]
Just 3
这篇关于差距函数,它使用foldl或foldr返回列表中两个元素的首次出现之间的整数距离.(Haskell)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!