u/CodeNameGodTri

▲ 15 r/haskell

implemented my own splitOn. Feedback needed

Hello everyone,

I'm a beginner looking for feedback. I wrote my own splitOn because words only splits on whitespace, and I didn’t want to pull in the split package just for one small utility function.

I ended up using a State monad approach. I know the state monad is probably overkill here, but I couldn’t think of a more idiomatic Haskell to mutate/build out a new list. I also used Seq to idiomatically access the last item efficiently O(1) instead of List

Please give me feedback on:

  • more idiomatic Haskell style
  • whether State here is considered bad practice
  • other cleaner solution not using State, I initally thought of fold but my brain froze
import Control.Monad.State (State, get, put, runState, execState)
import System.Environment (getEnv)
import Data.Sequence (Seq((:<|), (:|>), Empty), (|>), singleton)
import Data.Foldable (toList)

splitOn :: String -> Char -> [String]
splitOn text delimiter =
    toList $ execState (splitString text) (singleton "")

    where
    splitString :: String -> State (Seq String) ()
    splitString "" = return ()
    splitString (char : tail) = do
        parseChar char
        splitString tail


    parseChar :: Char -> State (Seq String) ()
    parseChar char = do
        currentState <- get
        if char == delimiter then put $ currentState |> ""
        else do
            let (front :|> lastItem) = currentState
                newLastItem = lastItem <> [char]
            put (front :|> newLastItem)

Appreciate any feedback or suggestions.

reddit.com
u/CodeNameGodTri — 4 days ago