简体   繁体   English

如何终止 Haskell 中的递归 function?

[英]How to terminate in a recursive function in Haskell?

I have a function that needs to terminate on a certain condition.我有一个 function 需要在特定条件下终止。 So for example say we have the following functions:例如,假设我们有以下功能:

func :: Int -> [[Int]] -> [[Int]]

func _ [] = []

func x (a:as) = func2 x a:func x as

func2 :: Int -> [Int] -> [Int]

func2 _ [] = []

func2 x (a:as) = x*a:func2 x as

Lets say that I want func one to be called as normal but whenever we get a negative value in the [[Int]] input, we terminate.假设我希望 func one 被正常调用,但是每当我们在 [[Int]] 输入中得到一个负值时,我们就会终止。 so we only deal with positive values.所以我们只处理正值。 so How could you make func2 send some signal to quit the whole process rather than continuing?那么你怎么能让 func2 发送一些信号来退出整个过程而不是继续呢?

First of all, your functions can be written more simply as首先,您的函数可以更简单地编写为

func1 x = map (func2 x)
func2 x = map (*x)

Now it is easy to change func2 to stop when a negative value is encountered:现在很容易将func2更改为在遇到负值时停止:

func2 x = map (*x) . takeWhile (> 0)

EDIT:编辑:

So if I understand this right, you want the entire computation to fail if a negative value is encountered.因此,如果我理解这一点,如果遇到负值,您希望整个计算失败。 One way to do this is to wrap the result in a Maybe .一种方法是将结果包装在Maybe中。 We can then write this in a monadic style:然后我们可以用 monadic 风格写这个:

func1 :: Int -> [[Int]] -> Maybe [[Int]]
func1 x = mapM (func2 x)

func2 :: Int -> [Int] -> Maybe [Int]
func2 x as = do
    guard $ all (>= 0) as
    return $ map (*x) as 

I'm not really sure what you mean, but I'll give it a shot:我不太确定你的意思,但我会试一试:

func _ [] = []
func x (a:as) | a < 0 = []
              | otherwise = func2 x a:func x as

This terminates the calculation for a negative value in the same way an empty list would do.这会以与空列表相同的方式终止负值的计算。 I hope this is what you want.我希望这是你想要的。

If you don't mind traversing the lists in func2 twice, this might work:如果您不介意遍历 func2 中的列表两次,这可能有效:

import Data.Maybe导入数据。也许

func:: Int -> [[Int]] -> [[Int]] func:: Int -> [[Int]] -> [[Int]]
func a xss = map fromJust. func a xss = map 来自Just。 takeWhile isJust. takeWhile 就是正义。 map (func2 a) $ xss map (func2 a) $ xss

func2:: Int -> [Int] -> Maybe [Int] func2:: Int -> [Int] -> 也许 [Int]
func2 a xs func2 a xs
| | any (< 0) xs = Nothing任何 (< 0) xs = 无
| | otherwise = Just.否则 = 只是。 map (*a) $ xs map (*a) $ xs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM