我正在嘗試撰寫一個函式join :: [[a]] -> [[a]],將串列中串列的最后一個字符與串列中串列的第一個字符連接起來。
join ["m"] = ["m"]
join ["a","b","c"] = ["b","c","a"]
join ["goodday", "world", "i", "love", "haskell"] = ["ooddayw","orldi","l","oveh","askellg"]
join ["the", "catcher", "in", "the", "rye"] = ["hec","atcheri","nt","her","yet"]
我正在嘗試撰寫僅使用 Haskell 中的基本函式(無庫函式)并且僅使用遞回來執行上述操作的代碼。
但是,我似乎無法實作一段正常作業的代碼。這是我到目前為止的代碼:
join :: [[a]] -> [[a]]
join [[a]] = [[a]]
join (n:ns:nss) | null nss == False = ((i n ns) : k (ns:nss))
| otherwise = []
是否有可能做到這一點?
uj5u.com熱心網友回復:
這是一個具有高階函式的解決方案,適用于整個資料操作范式:
import Control.Applicative (liftA2)
import Data.List (unfoldr)
import Control.Arrow ( (>>>) )
rotateds :: [[a]] -> [[a]]
rotateds =
map (splitAt 1) -- 1., 2.,
>>> concatMap (\(a,b) -> [a,b]) -- 3.,
>>> liftA2 ( ) (drop 1) (take 1) -- 4.,
>>> unfoldr (Just . splitAt 2) -- 5.,
>>> takeWhile (not . null) -- 5.,
>>> map (\[a,b] -> ( ) a b) -- 6.
它通過了您的所有測驗。所以是的,這是可能的。它的作業原理是:
1. turn each sublist in the input [ [a,b,c,...] , [d,......] , ... ]
2. into a pair [ ([a],[b,c,...]) , ([d], [...]) , ... ]
3. splice'em in [ [a],[b,c,...] , [d], [...] , ... ]
4. move the first letter over [ [b,c,...] , [d], ........ [a] ]
5. and restore the structure back to how it was
by reconstituting the pairs [ [[b,c,...] , [d]], ........... ]
6. and appending them together [ [ b,c,... , d ], ........... ]
將其轉換為直接的手動遞回是一項艱巨的任務,留給狂熱的學習者作為練習。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/366339.html
