Drkcore

28 06 2012 Haskell Tweet

HaskellでSchemeを実装する(エラーの導入)

Write Yourself a Scheme in 48 Hoursを読んでいる。4章のエラーチェッキングのあたり。

LispErrorを定義して、それをHaskellの組み込みのエラー関数で使えるようにする。

MonadErrorのインスタンスにすればthrowErrorとcatchErrorが使えるが、そのためにはEither型の左側をErrorクラスのインスタンスにする必要がある。

instance Error e => MonadError e (Either e) where
    throwError             = Left
    Left  l `catchError` h = h l
    Right r `catchError` _ = Right r

コード中ではここ。

type ThrowsError = Either LispError

instance Show LispVal where show = showVal
instance Show LispError where show = showError
instance Error LispError where
     noMsg = Default "An error has occurred"
     strMsg = Default

typeで別名をつけているのは取り回しを楽にするためかな?Error モナドを読んでも

type ParseMonad = Either ParseError

ってやってるし、エラーを取り扱う場合のお作法なのかなぁ。

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021