Haskell "pseudo-function"

I have a polynomial

data Poly a = Poly [a]

I would like to do something like fmap (take 3) polynomial, but I can’t, since it Poly’s actually not a functor in that fwhich I use in fmapcan only have a type [a] -> [b], not a -> b.

Is there an idiom or a way that I can express what I want?


EDIT: here is a function that does what I want

myMap :: ([a] ->[b]) -> P a -> P b
myMap f (P x) = P (f x)

using:

*Main> myMap (take 3) (P [1..])
P [1,2,3]

From the type of sig it can be seen that it is almost fmap, but not quite. I am obviously able to write code for myMap, but I just want to know if there is another idiom that I should use instead.

+5
source share
2 answers

, .

  • , Poly [a] [a].
  • .

, .

type Poly a = [a]

.

, , , newtype . , .

instance Newtype (Poly a) [a] where
  pack = Poly
  unpack (Poly x) = x

,

foo :: Poly a -> Poly a
foo = over Poly (take 3)

, myMap .


, , , , .

. , ,

data Poly a = Poly [(a, Int)]

Int - . , , . , Functor, .

instance Functor Poly where
    fmap f (Poly x) = Poly $ map f x

. ( , ) .

instance Functor Poly where
    fmap f (Poly x) = Poly $ map (first f) x
+10

, , , :

{-#LANGUAGE GADTs #-}

data Poly a where
   Poly :: [b] -> Poly [b]

Poly, a, a :

~% ghci Poly.hs
GHCi, version 6.8.2: http://www.haskell.org/ghc/  :? for help
Loading package base ... linking ... done.
[1 of 1] Compiling Main             ( Poly.hs, interpreted )
Ok, modules loaded: Main.
*Main> :k Poly
Poly :: * -> *
*Main> :t Poly
Poly :: [b] -> Poly [b]
*Main> case Poly [1,2,3] of _ -> 0
0
*Main> case Poly 4 of _ -> 0

<interactive>:1:10:
    No instance for (Num [b])
      arising from the literal `4' at <interactive>:1:10
    Possible fix: add an instance declaration for (Num [b])
    In the first argument of `Poly', namely `4'
    In the scrutinee of a case expression: Poly 4
    In the expression: case Poly 4 of _ -> 0
*Main> case Poly True of _ -> 0

<interactive>:1:10:
    Couldn't match expected type `[b]' against inferred type `Bool'
    In the first argument of `Poly', namely `True'
    In the scrutinee of a case expression: Poly True
    In the expression: case Poly True of _ -> 0

Functor :

instance Functor Poly where
  fmap f (Poly x) = Poly (f x)

Couldn't match expected type `[b1]' against inferred type `b2'
  `b2' is a rigid type variable bound by
       the type signature for `fmap' at <no location info>
In the first argument of `Poly', namely `(f x)'
In the expression: Poly (f x)
In the definition of `fmap': fmap f (Poly x) = Poly (f x)

. , myMap:

polymap f (Poly x) = Poly (f x)

,

GADT pattern match in non-rigid context for `Poly'
  Tell GHC HQ if you'd like this to unify the context
In the pattern: Poly x
In the definition of `polymap': polymap f (Poly x) = Poly (f x)

, :

 polymap :: ([a] -> [b]) -> Poly [a] -> Poly [b]

fmap. Functor " ", . undefined :: Poly Int, . , , , ( , -, , ghc, ). , .

+2

All Articles