使用Gtk2hs和Glade的Haskell BASE64编码器GUI



我有以下问题。我尝试使用Gtk2Hs和Glade在Haskell中为BASE64编码器创建一个简单的GUI。这是Haskell中BASE64编码器的示例。

{-# LANGUAGE OverloadedStrings #-}
import Data.ByteString.Base64
import Data.ByteString.Char8
main = do
    print $ unpack $ encode "Hello, world!"
    print $ decode "SGVsbG8sIHdvcmxkIQ=="

现在我想为这个例子创建GUI,但是我希望能够输入任何要编码的值。我已经创建了模板与以下组件:- entry1(输入要编码的值)-按钮(开始生成)- entry2(查看生成值)

我的haskell代码:
entry1 <- builderGetObject hello castToEntry "entry1"
entry2 <- builderGetObject hello castToEntry "entry2"
button <- builderGetObject hello castToButton "button"
onClicked button $ do
    name2 <- get entry1 entryText
    set entry2 [ entryText := unpack $ encode name2]
当编译 时,我收到以下错误
Couldn't match expected type `ByteString' with actual type `String'
In the first argument of `encode', namely `name2'
In the second argument of `($)', namely `encode name2'
In the second argument of `(:=)', namely `unpack $ encode name2'

name2String类型,而encode需要ByteString类型。最简单的方法就是使用Data.ByteString.Char8中的pack函数进行转换。但是有一个问题:它只适用于ASCII码点。如果用户输入非ascii字符会发生什么?

相反,我建议使用utf8编码您的文本。要做到这一点,我将使用text包,它看起来像:

import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
encode $ TE.encodeUtf8 $ T.pack name2

最新更新