如何在Haskell中将字符串拆分为字符串列表?

问题描述 投票:1回答:1
split sep str = foldr op [[]] str
    where op (x:xs) (y:ys)
              | x == sep = ([]:y)
              | otherwise = ((x:y):ys)

我正在尝试从一个字符串开始分割一个字符串,并进入一个字符串列表。此代码有什么问题?

string haskell fold
1个回答
0
投票

([]:y)没有意义,因为它应该是项目列表,但是y是项目列表。即使类型系统不会抱怨(例如由于使用Python之类的动态类型语言),也没有太大意义,因为您删除了ys,因此将省略其余的递归。

[另一个问题是您将(x:xs)写为第一个参数,这意味着您折叠的列表中的项目是列表本身,但是鉴于我对它的正确理解,您折叠了String,因此该元素是简单字符:

您可以通过返回[]:y:ys来解决此问题:

split :: (Foldable f, Eq a) => a -> f a -> [[a]]
split sep str = foldr op [[]] str
    where op x ~(y:ys)
              | x == sep = []:y:ys
              | otherwise = (x:y):ys

例如:

Prelude> split '-' "this-is-kebab-case"
["this","is","kebab","case"]
© www.soinside.com 2019 - 2024. All rights reserved.