Como aplicar uma função polimórfica a ambos os lados de um Either?
Eu tentei isso:
type TestT = Either Int Float
testM :: (a -> a) -> TestT -> TestT
testM f (Left x) = Left (f x)
testM f (Right x) = Right (f x)
mas não funciona, tem como fazer isso? Dei uma olhada em volta e tudo parecido foi realmente complicado e limitado.
Mensagem de erro, conforme exigido:
Main.hs:101:28: error:
• Couldn't match expected type ‘a’ with actual type ‘Int’
‘a’ is a rigid type variable bound by
the type signature for:
testM :: forall a. (a -> a) -> TestT -> TestT
at Main.hs:100:1-35
• In the first argument of ‘f’, namely ‘x’
In the first argument of ‘Left’, namely ‘(f x)’
In the expression: Left (f x)
• Relevant bindings include
f :: a -> a (bound at Main.hs:101:7)
testM :: (a -> a) -> TestT -> TestT (bound at Main.hs:101:1)
Respostas
Não acho que você possa fazer isso no idioma base. Conforme mencionado nos comentários, pode ser necessário habilitar algumas extensões, como RankNTypes.
Como todos os tipos envolvidos são numéricos, é tentador usar uma função de incremento, como (+1) como função polimórfica.
Vamos tentar em ghci
:
$ ghci
GHCi, version 8.6.5: http://www.haskell.org/ghc/ :? for help
λ>
λ> type TestT = Either Int Float
λ>
λ> :set +m
λ>
λ> :set -XRankNTypes
λ> :set -XScopedTypeVariables
λ>
λ> {-
|λ> let { testM :: (forall a. Num a => a -> a) -> TestT -> TestT ;
|λ> testM fn (Left x) = Left (fn x) ;
|λ> testM fn (Right x) = Right (fn x) }
|λ> -}
λ>
λ> :type testM
testM :: (forall a. Num a => a -> a) -> TestT -> TestT
λ>
λ> testM (+3) (Left 42)
Left 45
λ>
λ> testM (+3) (Right 3.14159)
Right 6.14159
λ>
Nota 1: Se você omitir as extensões de idioma, ele será interrompido, com uma mensagem sugerindo RankNTypes.
Nota 2: se você usar em forall a. Num a => (a -> a)
vez de (forall a. Num a => a -> a)
, ele também quebra.
Nota 3: Algumas técnicas anteriores aqui: SO-q38298119 com um comentário útil de Alexis King.
Uma maneira de fazer isso é com o Bifunctor:
Prelude> :m +Data.Bifunctor
Prelude Data.Bifunctor> bimap show show (Left 3)
Left "3"
Prelude Data.Bifunctor> bimap show show (Right 'x')
Right "'x'"
Prelude Data.Bifunctor>