Comment appliquer une fonction polymorphe aux deux côtés d'un soit?

Dec 06 2020

J'ai essayé ceci:

type TestT = Either Int Float

testM :: (a -> a) -> TestT -> TestT
testM f (Left x) = Left (f x)
testM f (Right x) = Right (f x)

mais cela ne fonctionne pas, y a-t-il un moyen de le faire? J'ai fait quelques recherches et tout ce qui était similaire était vraiment compliqué et limité.

Message d'erreur, comme demandé:

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)

Réponses

3 jpmarinier Dec 06 2020 at 03:30

Je ne pense pas que vous puissiez le faire dans la langue de base. Comme mentionné dans les commentaires, vous devrez peut-être activer quelques extensions, telles que RankNTypes.

Comme tous les types impliqués sont numériques, il est tentant d'utiliser une fonction d'incrémentation, telle que (+1) comme fonction polymorphe.

Essayons ci-dessous 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
 λ> 

Remarque 1: Si vous omettez les extensions de langue, cela se rompt, avec un message faisant allusion à RankNTypes.

Remarque 2: si vous utilisez à la forall a. Num a => (a -> a)place de (forall a. Num a => a -> a), cela se brise également.

Note 3: Quelques antécédents ici: SO-q38298119 avec un commentaire utile d'Alexis King.

2 DavidFox Dec 09 2020 at 10:26

Une façon de faire est avec 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>