gpt4 book ai didi

haskell - 删除 haskell 语句中的括号

转载 作者:行者123 更新时间:2023-12-02 06:16:30 25 4
gpt4 key购买 nike

我正在尝试使用折叠和追加进行字节串操作。请看下面的代码。

import qualified Data.ByteString.Char8 as C

selectSource :: [String] -> C.ByteString
selectSource xs = C.append (foldl addSource emptySource xs) (C.pack "<head>")

addSourceemptySource 是相应定义的。括号看起来有点难看,我想在 selectSource 函数中将它们删除为

C.append $ foldl addSource emptySource xs $ C.pack "<head>"

但未能这样做并收到一条错误消息说

Couldn't match expected type ‘C.ByteString -> C.ByteString’
with actual type ‘C.ByteString’
The first argument of ($) takes one argument,
but its type ‘SourceByteString’ has none
In the second argument of ‘($)’, namely
‘foldl addSource emptySource [] $ C.pack "<head>"’

这行得通

C.append (foldl addSource emptySource xs) $ C.pack "<head>"

但它还有最后一对括号。

最佳答案

您可以使用 C.append 来编写不带括号的代码作为infix operator .

selectSource :: [String] -> C.ByteString
selectSource xs = foldl addSource emptySource xs `C.append` C.pack "<head>"

ByteString我们有 Monoid 带有 mappend = append 的实例你可以用中缀 Monoid 写得更优雅运算符(operator) <> .

import Data.Monoid

selectSource :: [String] -> C.ByteString
selectSource xs = foldl addSource emptySource xs <> C.pack "<head>"

如果启用 OverloadedStrings 你可以写像 "<head>" 这样的字符串文字并将它们用作 ByteString秒。 ByteStringfromStringpackpackChars视情况而定(它是 pack 代表 Char8 ByteString s)。这可以去掉一组括号,这样你就可以写 selectSource没有任何括号的无点。

{-# LANGUAGE OverloadedStrings #-}

selectSource :: [String] -> C.ByteString
selectSource = flip C.append "<head>" . foldl addSource emptySource

如果您更喜欢运算符 flip你可以用 operator section 来写这个反而。这需要在运算符部分语法的运算符周围加上括号。运算符部分括号不会打扰我,因为我从不嵌套它们。

{-# LANGUAGE OverloadedStrings #-}    
import Data.Monoid

selectSource :: [String] -> C.ByteString
selectSource = (<> "<head>") . foldl addSource emptySource

使用任何一个无点定义,我们都可以添加额外的功能,如 C.init没有弄乱括号。

selectSource' :: [String] -> C.ByteString
selectSource' = flip C.append "<head>" . C.init . foldl addSource emptySource

selectSource' :: [String] -> C.ByteString
selectSource' = (<> "<head>") . C.init . foldl addSource emptySource

关于haskell - 删除 haskell 语句中的括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29484234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com