Jon*_*han 2 string haskell slice
我试图找到与Python等效的Haskell:
>>>"This is a test"[5:9]
'is a'
Run Code Online (Sandbox Code Playgroud)
我正在使用该Data.Text模块,如果有什么不同的话。
通常使用drop :: Int -> Text -> Text和take :: Int -> Text -> Text来获取潜台词的一部分。我们可以将两者结合起来做出某种substring:
import Data.Text as Tx(Text, drop, take)
substring :: Int -> Int -> Tx.Text -> Tx.Text
substring start length = Tx.take length . Tx.drop start
Run Code Online (Sandbox Code Playgroud)
或者如果我们想使用结束索引(独占),我们可以创建一个slice函数:
import Data.Text as Tx(drop, take)
slice :: Int -> Int -> Tx.Text -> Tx.Text
slice start end = Tx.take (end-start) . Tx.drop start
Run Code Online (Sandbox Code Playgroud)
然后我们可以像这样使用它:
Prelude Tx> slice 5 9 "This is a test"
"is a"
Run Code Online (Sandbox Code Playgroud)
这并不完全等同于 Python 的切片表示法,因为例如 Python 使用负索引作为从最后一个元素(即-1最后一个元素)开始计数的一种方式,我们可以使用它'foobar'[-5:-2]来获得一个切片,其中索引意味着“取一个从最后四个元素切片到最后一个元素”。
使用take功能简单:
substring :: Int -> Int -> Text -> Text
substring start end text = take (end - start) (drop start text)
Run Code Online (Sandbox Code Playgroud)
此外,您可以根据Data.Text.take和定义函数drop,这两个函数都来自Data.Text库:
slice :: Int -> Int -> Text -> Text
slice a b = (Data.Text.take (b - a)) . (Data.Text.drop a)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2405 次 |
| 最近记录: |