2
shortLinesOnly :: IO ()
shortLinesOnly = interact result
    where
        shortLength     = 11
        onlyShorts      = (<= shortLength) . length
        shortLines      = filter onlyShorts . lines
        result          = unlines . shortLines
        interact result = getContents >>= putStr . result

在上面的代码中,我如何以无点样式编写交互函数。

4

2 回答 2

11

一步步:

interact r = getContents >>= putStr . r
interact r = (getContents >>=) (putStr . r)
interact r = (getContents >>=) $ (putStr .) $ r
interact = (getContents >>=) . (putStr .)
于 2011-09-11T13:23:16.803 回答
6

最好的答案是:不要。对于这个特定的例子,唯一的改变是你的代码可读性会降低。您原来的尖尖变体非常好。

在某些情况下,最好避免使用无点样式。这是其中之一,因为您的论点没有经历线性数据流。它更用于为其他东西构建数据流。例子:

-- Bad: Pointy linear data flow description.
chunksOf :: Int -> [a] -> [[a]]
chunksOf n xs =
    takeWhile (not . null) (map (take n) (iterate (drop n) xs))

-- Good: Pointfree linear data flow description.
chunksOf :: Int -> [a] -> [[a]]
chunksOf n =
    takeWhile (not . null) . map (take n) . iterate (drop n)

-- Bad: Now exaggerating with pointfree style.
chunksOf :: Int -> [a] -> [[a]]
chunksOf =
    liftA2 ((.) (.) . (.) $ takeWhile (not . null))
           (map . take)
           (iterate . drop)
于 2011-09-11T13:49:32.737 回答