簡體   English   中英

為什么這兩個Haskell“展開”功能不同?

[英]Why are these two Haskell “unfold” functions different?

我正在學習Haskell,現在正在與Maybe Class一起練習。 我必須創建一個將f(“ Maybe function”)重復應用於a(及其后續結果)的函數,直到f a返回Nothing為止。 例如,f a0 = Just a1,f a1 = Just a2,...,f an = Nothing。 然后

unfold f a0 = [a0,a1,...,an]

我已經嘗試過了,並且得到了:

unfold :: (a- > Maybe a) -> a -> [a]
unfold f a = case f a of
                 Just n -> n: unfold f a
                 Nothing -> []

問題在於解決方案是:

unfold' :: ( a -> Maybe a) -> a -> [a]
unfold' f a = a : rest ( f a )
     where rest Nothing = []
           rest ( Just x ) = unfold' f x

而且我的程序不能像解決方案那樣工作。 也許我使用了錯誤的“ case of”,但是我不確定。

使用case是可以的,但是請看一下您在列表中的新值位置以及解決方案的位置。

testFunc = const Nothing

unfold  testFunc 1 == []  -- your version prepends only if f a isn't Nothing
unfold' testFunc 1 == [1] -- the solution _always_ prepends the current value

另外,您一直在使用相同的值。

unfold :: (a -> Maybe a) ->a -> [a]
unfold f a = a : case f a of -- cons before the case
    Just n  -> unfold f n    -- use n as parameter for f
    Nothing -> []

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM