Search code examples
haskellparsec

How can I inline this function?


I have two functions, but one of the functions is only called from the other, so I would like to inline the helper function. My code looks like this:

data PoS =  N | V | Adj | Adv | Phr

posEntity :: Parser PoS
posEntity = 
    do pos <- string "N." <|>
              string "V." <|>
              string "Adj." <|>
              string "Adv." <|>
              string "Phr."
       return (posToPoS pos)
    <?> "part of speech"

posToPoS pos
    | pos == "N." = N
    | pos == "V." = V
    | pos == "Adj." = Adj
    | pos == "Adv." = Adv
    | pos == "Phr." = Phr

Clearly the posToPoS should be inlined, but I am unsure of the syntax required to do such a thing.

Thanks!


Solution

  • GHC probably will automatically inline it when optimizing. However, to force it to do so, simply add {-# INLINE posToPoS #-} somewhere in the code, preferably right next to the definition of posToPoS.

    For making it local, so that only posEntity can see it, you want a where clause. Define it as such:

    data PoS =  N | V | Adj | Adv | Phr
    
    posEntity :: Parser PoS
    posEntity = 
        do pos <- string "N." <|>
                  string "V." <|>
                  string "Adj." <|>
                  string "Adv." <|>
                  string "Phr."
           return (posToPoS pos)
        <?> "part of speech" where
            posToPoS pos
                | pos == "N." = N
                | pos == "V." = V
                | pos == "Adj." = Adj
                | pos == "Adv." = Adv
                | pos == "Phr." = Phr