Split a string by a chosen character in haskell

给你一囗甜甜゛ 提交于 2020-01-05 06:42:13

问题


I'm trying to split a string every time there is a chosen character. So if I receive "1,2,3,4,5", and my chosen character is "," the result is a list such as ["1","2","3","4","5"].

I've been looking through the already answered questions in here and they point me to using splitOn. However, when i try to import Data.List.Split in order to use it, Haskell gives me the following error: Could not find module ‘Data.List.Split’ . When I tried to just use splitOnwithout importing the module, it showed me Variable not in scope: splitOn.

So my questions are,

  1. Is it normal that i'm getting this error? Is splitOn a viable option or should I just try something else?
  2. What other simple solutions are there?

I can just write something that will do this for me but I'm wondering why I'm not able to import Data.List.Split and if there are other simpler options out there that I'm not seeing. Thank you!


回答1:


If you're using GHC it comes with the standard Prelude and the modules in the base package, and perhaps a few other packages.

Most packages, like the split package (which contains the Data.List.Split module), aren't part of GHC itself. You'll have to import them as an explicit compilation step. This is easiest done with a build tool. Most Haskellers use either Cabal or Stack.

With Stack, for example, you can add the split package to your package.yaml file:

dependencies:
- base >= 4.7 && < 5
- split

You can also load an extra package when you use Stack to start GHCi. This is useful for ad-hoc experiments.




回答2:


‘Data.List.Split’ is not in prelude and needs to be installed as a dependency package. Install command depends on environment you are using: ‘stack install split’ for stack ‘cabal install split’ for cabal




回答3:


Basically this is a foldring job. So you may simply do like

λ> foldr (\c (s:ss) -> if c == ',' then "":s:ss else (c:s):ss) [""] "1,2,3,42,5"
["1","2","3","42","5"]

So;

splitOn x = foldr (\c (s:ss) -> if c == x then "":s:ss else (c:s):ss) [""]

However this will give us reasonable but perhaps not wanted results such as;

λ> splitOn ',' ",1,2,3,42,5,"
["","1","2","3","42","5",""]

In this particular case it might be nice to trim the unwanted characters off of the string in advance. In Haskell though, this functionality i guess conventionally gets the name

dropAround :: (Char -> Bool) -> String -> String
dropAround b = dropWhile b . dropWhileEnd b

λ> dropAround (==',') ",1,2,3,42,5,"
"1,2,3,42,5"

accordingly;

λ> splitOn (',') . dropAround (==',') $ ",1,2,3,42,5,"
["1","2","3","42","5"]


来源:https://stackoverflow.com/questions/59225502/split-a-string-by-a-chosen-character-in-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!