使这个功能默认

dim*_*mid 1 haskell pointfree

我想使这个功能无点,以简化它.我明确地传递长度而不是计算它,因为我还需要它用于其他函数,并且我只想计算它一次.我已经设法摆脱目标字符串参数,但与其他两个挣扎.

-- 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)

dim*_*mid 7

关注@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)

  • 这是一种部分功能,它也像糖蜜一样慢.这种组合非常糟糕. (6认同)
  • 顺便说一句,这远远优于您开始使用的代码.我对`!!`过敏. (2认同)

red*_*neb 5

我非常怀疑通过以无点样式编写这个特定函数可以变得更简单.例如,这是我从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)

  • 一如既往地从pointfree实现水晶般清晰的实现. (9认同)
  • @dimid不,他们没有取消.请记住,函数应用程序是左关联的,所以例如`flip flip snd`与`(flip flip)snd`和_not_`flip(flip snd)`相同. (3认同)