簡體   English   中英

自然變換作為Haskell中的一個參數

[英]Natural transformation as an argument in Haskell

我正在尋找一種方法來定義自然變換作為傳遞給函數的簡單參數。

讓我們以一個簡單的函數為例:

mapK :: (m Int -> IO Int) -> Kleisli m Bool Int -> Kleisli IO Bool Int
mapK toIO kleisli = Kleisli (\bool -> toIO $ runKleisli kleisli bool)

整潔,但如果我改為:

mapK :: (m a -> IO a) -> Kleisli m Bool Int -> Kleisli IO Bool Int
mapK toIO kleisli = Kleisli (\bool -> toIO $ runKleisli kleisli bool)

我得到了Int不是a的錯誤(在那里並不奇怪)。

我知道可以使用約束來實現它:

class NaturalTransformation f g where
  transform :: f a -> g a

mapK :: (NaturalTransformation m IO) => Kleisli m Bool Int -> Kleisli IO Bool Int

但我很好奇是否也可以用普通的論據來做。

當然,你只需要求實現者而不是調用者來選擇變量:

{-# LANGUAGE RankNTypes #-}
mapK :: (forall a. m a -> IO a) -> Kleisli m Bool Int -> Kleisli IO Bool Int
-- implementation is exactly as before
mapK toIO kleisli = Kleisli (toIO . runKleisli kleisli)
-- OR, with TypeApplications also on,
mapK toIO = coerce @(_ (Bool -> _ Int)) (toIO.)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM