如何实现无点交互?

发布于 2024-12-04 01:18:29 字数 386 浏览 1 评论 0原文

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

在上面的代码中,我如何以点自由风格编写interact函数。

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

In the above code how can I write the interact function in point free style.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ぽ尐不点ル 2024-12-11 01:18:29

步步:

interact r = getContents >>= putStr . r
interact r = (getContents >>=) (putStr . r)
interact r = (getContents >>=) $ (putStr .) $ r
interact = (getContents >>=) . (putStr .)

Step by step:

interact r = getContents >>= putStr . r
interact r = (getContents >>=) (putStr . r)
interact r = (getContents >>=) $ (putStr .) $ r
interact = (getContents >>=) . (putStr .)
与往事干杯 2024-12-11 01:18:29

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

在某些情况下,最好避免 pointfree 风格。这是其中之一,因为你的论点不经历线性数据流。它更适合用来为其他东西构建数据流。例子:

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

The best answer is: Don't. For this particular example the only change that would make is that your code would be less readable. Your original pointy variant is perfectly fine.

In certain cases it is better to avoid pointfree style. This is one of them, because your argument does not undergo linear data flow. It is rather used to build the data flow for something else. Example:

-- 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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文