簡體   English   中英

Haskell包裝函數實現

[英]Haskell wrap function implementation

我對此功能的實現有疑問:

類型簽名

wrap :: Int -> a -> [a] -> [a]

目的

在列表xs中的第n個位置插入x

例子

wrap 1 '+' "a" : "+a+"

wrap 2 '+' "a" : "+a"

wrap 2 '+' "abcd" : "+ab+cd+"

定義

wrap _ _ [] = []
wrap n x xs = insertAfter 0 xs
        where insertAfter = undefined

一個人怎么能做到這一點,我只是想不通。 編輯:

完整的問題:實現函數wrap,該函數將生成一個列表,該列表以wrap的第二個參數(x)開頭,然后是wrap的第三個參數(xs)的所有條目,如wrap的第一個參數(n)所示。 重復直到第三個參數為空。 在結果列表中,第n個元素應等於x。 如果xs的長度可以被n整除,請在最后插入x。 提示:根據函數insertAfter來實現函數包裝,該函數需要一個數字m和一個元素列表xs,當元素從xs中移除時,m會減少m,並且在m達到0時插入x。

我幾乎明白了:

 wrap _ _ [] = []
 wrap n x xs = insertAfter 0 xs
   where insertAfter 0 xs = x : insertAfter n xs
         insertAfter _ [] = undefined
         insertAfter n xs = take n xs ++ (wrap n x (drop n xs))

但是使用示例:wrap 2'+'“ abcd”:wrap 2'+'“ abcd”:“ + ab + cd +”我得到了“ + ab + cd”,所以缺少了'+'。

我已經自由更改了傳遞給insertAfter的參數。 這是非常往往更方便一點倒計時 ,而不是計數 ,並在這里這是事實也是如此。

wrap :: Int -> a -> [a] -> [a]
wrap _ _ [] = []
wrap n delim = insertAfter n
  where
     -- We've reached zero. So we insert the delimiter and
     -- reset the counter to n.
     insertAfter 0 xs = delim : insertAfter n xs
     -- All done
     insertAfter _ [] = ???
     -- Still some work to do
     insertAfter k (y : ys) = ???

順便說一句:您所說的“合同”就是我們所說的類型簽名 實際的合同通常會提供更多有關參數期望值和結果保證值的詳細信息。 例如,這里的約定將指定要wrap的第一個參數必須為正,並解釋該函數的作用。

您可以執行以下操作

wrap :: Int -> a -> [a] -> [a]
wrap _ _ [] = []
wrap n c cs | n == length cs = c:cs++[c]
            | otherwise      = c:x ++ wrap n c y
              where (x,y) = splitAt n cs

n == length cs條件是必需的,因為splitAt 2..n "a"splitAt 1 "a"給出("a","") 我也總是假設n >= 1

暫無
暫無

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

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