Last active
April 4, 2017 02:47
-
-
Save aiya000/4e4b7c5ad50ef646277ebcba63e006bc to your computer and use it in GitHub Desktop.
「GenerarizedNewTypeDerivingで自分用Monadを作る」ってなに!?(具体例編) ref: http://qiita.com/aiya000/items/f6e7103c99066707f3cf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE GeneralizedNewtypeDeriving #-} | |
{-# LANGUAGE OverloadedStrings #-} | |
import Data.String (IsString) | |
import Data.Text (Text) | |
import qualified Data.Text.IO as TIO | |
newtype MyString = MyString { unMyString :: Text } | |
deriving (IsString) -- GenerarizedNewTypeDerivingがないと、ここを書けない | |
txt :: MyString | |
txt = "アホ毛" | |
main :: IO () | |
main = TIO.putStrLn . unMyString $ txt |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- | Current state of ElinParser | |
data ElinState = ElinState | |
{ _parseLogs :: [ParseLog] | |
, _parseNestLevel :: Int | |
} deriving (Show) | |
-- | Parser with parsing logs | |
newtype ElinParser a = ElinParser { _runElinParser :: ParsecT Dec Text (State ElinState) a } | |
deriving ( Functor, Applicative, Monad | |
, Alternative, MonadPlus | |
, MonadState ElinState, MonadParsec Dec Text | |
) | |
-- | A log of ElinParser | |
data ParseLog = Message Text -- ^ Simple message | |
| ParsedItem Text -- ^ Ex: '(', ''', ')' or some symbol | |
deriving (Show) | |
-- | Run parser and extract result and logs | |
runElinParser :: ElinParser a -> Text -> (Either (ParseError Token Dec) a, [ParseLog]) | |
runElinParser parser source = | |
let initialState = ElinState [] 0 | |
bareness = _runElinParser parser | |
(result, ElinState logs _) = flip runState initialState $ runParserT bareness "" source | |
in (result, reverse logs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment