関数から始めたとしましょう
fromJust Nothing = error "fromJust got Nothing!"
fromJust (Just x) = x
次に、エラーメッセージを改善するために、テンプレートHaskellを介してソース情報を追加したいと思います。関数にパラメーターを追加できると想像してみましょう
fromJust' loc Nothing = error $ "fromJust got Nothing at " ++ (loc_filename loc)
fromJust' loc (Just x) = x
次に、次のfromJust
ようなソースコードで使用できるマクロがあります。
x = $fromJust $ Map.lookup k m
ハック
準引用符を使用し、ソースファイル名の文字列を持ち上げることで、なんとかハッキングできました。Loc
Liftインスタンスがないようです。もっと良い方法はありますか?
fromJustErr' l (Nothing) =
error $ printf "[internal] fromJust error\
\\n (in file %s)" l
fromJustErr' l (Just x) = x
fromJustErr = do
l <- location
let fn = loc_filename l
fnl :: Q Exp = TH.lift fn
[| fromJustErr' $fnl |]
ありがとう!
(使用するよりもファンクターfmap
を介して詰め込む方が良いことは知っていますが、時々ハックする必要があります。)Maybe
fromJust