我想使这个功能无点,以简化它.我明确地传递长度而不是计算它,因为我还需要它用于其他函数,并且我只想计算它一次.我已经设法摆脱目标字符串参数,但与其他两个挣扎.
-- Cycle with respect to whitespace (currently only spaces).
-- Given a source string and its length, and a longer target string
-- (which may contain spaces) match the source to target such that:
-- 1. both will have the same length
-- 2. spaces in the target string will remain spaces
-- 3. chars from the source string will be cycled
--
-- Example:
-- src: "ALLY", len: 4
-- target: "MEET AT DAWN"
-- Result: "ALLY AL LYAL"
cycleWS :: String -> Int -> String -> String
cycleWS str len = fst . (foldr (\x (s, n) -> if x == ' ' then (s ++ " ", n) else (s ++ [str !! (n `mod` len)], n + 1)) ("", 0))
Run Code Online (Sandbox Code Playgroud)
关注@Reid Barton的建议:
-- Cycle with respect to whitespace (currently only spaces).
-- Given a source string and its length, and a longer target string
-- (which may contain spaces) match the source to target such that:
-- 1. both will have the same length
-- 2. spaces in the target string will remain spaces
-- 3. chars from the source string will be cycled
--
-- Example:
-- src: "ALLY", len: 4
-- target: "MEET AT DAWN"
-- Result: "ALLY AL LYAL"
cycleWS :: String -> String -> String
cycleWS = align . cycle
-- Align with respect to spaces.
-- Given two strings, source and target, align the source to target such that:
-- 1. both will have the same length
-- 2. spaces in the target string will remain spaces
-- Assume the source string is long enough
align :: String -> String -> String
align [] _ = []
align _ [] = []
align (x:xs) (y:ys) = if isSpace y then y : align (x:xs) ys else x : align xs ys
Run Code Online (Sandbox Code Playgroud)
我非常怀疑通过以无点样式编写这个特定函数可以变得更简单.例如,这是我从pointfree.io得到的:
cycleWS = ((fst .) .) . flip flip (([]), 0) . (foldr .) . flip flip snd . ((flip . (ap .)) .) . flip flip fst . ((flip . ((.) .) . flip (ap . (ap .) . (. ((,) . (++ " "))) . (.) . if' . (' ' ==))) .) . flip flip (1 +) . ((flip . (liftM2 (,) .) . flip ((.) . (++))) .) . flip flip ([]) . ((flip . ((:) .)) .) . (. flip mod) . (.) . (!!)
Run Code Online (Sandbox Code Playgroud)