Jak zastosować funkcję polimorficzną do obu stron Albo?
Próbowałem tego:
type TestT = Either Int Float
testM :: (a -> a) -> TestT -> TestT
testM f (Left x) = Left (f x)
testM f (Right x) = Right (f x)
ale to nie działa, czy jest jakiś sposób, aby to zrobić? Rozejrzałem się trochę i wszystko podobne było naprawdę skomplikowane i ograniczone.
Komunikat o błędzie, zgodnie z wymaganiami:
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)
Odpowiedzi
Nie sądzę, że możesz to zrobić w języku podstawowym. Jak wspomniano w komentarzach, może być konieczne włączenie kilku rozszerzeń, takich jak RankNTypes.
Ponieważ wszystkie zaangażowane typy są liczbowe, kuszące jest użycie funkcji przyrostowej, takiej jak (+1), jako funkcji polimorficznej.
Spróbujmy pod 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
λ>
Uwaga 1: Jeśli pominiesz rozszerzenia językowe, zepsuje się, z komunikatem wskazującym na RankNTypes.
Uwaga 2: jeśli użyjesz forall a. Num a => (a -> a)
zamiast (forall a. Num a => a -> a)
, to również się zepsuje.
Uwaga 3: Tutaj trochę stanu techniki: SO-q38298119 z przydatnym komentarzem Alexisa Kinga.
Jednym ze sposobów jest użycie 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>