Split a string by a chosen character in haskell

前端 未结 3 1490
北恋
北恋 2021-01-24 04:58

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 l

相关标签:
3条回答
  • 2021-01-24 05:22

    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"]
    
    0 讨论(0)
  • 2021-01-24 05:24

    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.

    0 讨论(0)
  • 2021-01-24 05:25

    ‘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

    0 讨论(0)
提交回复
热议问题