我試圖將 a 拆分Data.Text為 a [Text],對該串列的元素運行一個函式,然后是unword它們,或者intercalate它們。但型別不匹配。而不是Text -> Text我得到一個[Text] -> [Text]功能。
import Data.Text(Text, pack, unpack, intercalate, split)
f = split (\x-> x==' ') . intercalate (pack " ")
:t f
--Prints for some reason: f :: [Text] -> [Text]
g = split (\x-> x==' ') . Data.Text.unwords
:t g
-- Prints again: g :: [Text] -> [Text]
我怎樣才能得到一個Text -> Text功能?
uj5u.com熱心網友回復:
您的函式型別是:
split :: (Char -> Bool) -> Text -> [Text]
intercalate :: Text -> [Text] -> Text
如果您要在沒有函陣列合的情況下撰寫它,代碼將如下所示:
f :: Text -> Text
f text = intercalate (pack " ") (split (==' ') text)
-- or also: intercalate (pack " ") $ split (==' ') text
所以你首先要做的是分裂然后插入。看看函陣列合是如何定義的:
(.) :: (b -> c) -> (a -> b) -> a -> c
(.) f g = \x -> f (g x)
它接受兩個函式f,g并回傳一個f(g(x))首先應用的函式g,然后是f。所以,當你寫
f = split (\x-> x==' ') . intercalate (pack " ")
你會得到的是:
f :: [Text] -> [Text]
f = \x -> intercalate (pack " ") (split (==' ') x)
-- first splitting and then intercalating
你想要的代碼是:
f :: Text -> Text
f = intercalate (pack " ") . split (== ' ')
-- equivalent to:
-- f = \x -> intercalate (pack " ") (split (== ' ') x)
-- where you first split and then intercalate
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/487872.html
