Is it possible to write a function in haskell: (r & # 8594; [a]) & # 8594; [r & # 8594; a])?

The opposite seems possible. Since I believe that lists are products, and ->

is exponentiation, (a*a*a...)^r = (a^r)*(a^r)....

Since how can we determine the opposite [a->r] -> a -> [r]

, shouldn't it be determined?

+3


source to share


3 answers


If you want to fix the size of the feature list, it will work.

dn :: [r -> a] -> (r -> [a])
dn fns r = map ($ r)

up :: Int -> (r -> [a]) -> [r -> a]
up n f = tabulate n (\i r -> f' r !! i)
  where 
   f' = cycle . f
   tabulate n f = map f [0..n-1]

      

Now we can get up

as "view" to the left of dn

... assuming we shuffle some length information:

id1 :: [r -> a] -> [r -> a]
id1 ls = up (length ls) (dn ls)

      



and it could be the "kind" of the right inverse to dn

if we magically know (a) that for each the r

length of the list of results is the [a]

same and (b) we know that the length is (below magic

)

id2 :: (a -> [b]) -> a -> [b]
id2 f = dn . up magic

      

This answer is basically equivalent to the comment copumpkin

for the answer leftroundabout

, but instead of executing it using types, I manually pass in the (fixed) length information. If you play around a bit with up

and dn

, you'll see why this doesn't work at all for lists at all.

+4


source


[a] โ‰… a*a*...

only used for infinite lists. For them, your requested function is actually quite simple, although the implementation of na & iuml; ve is not very efficient:

type InfiList = []

unwind :: (r -> InfiList a) -> InfiList(r -> a)
unwind f = [ \x -> f x !! n | n <- [0..] ]

      



Actually [a] โ‰… 1 + a * (1 + a * (1 + ...))

; the power law does not work here.

+8


source


Intuitively, this is not possible if the length of the lists is not known in advance.

This is because the type r -> [a]

roughly matches the following:

  • Make an input like r

  • Print a natural number n

    (including infinite)
  • List values โ€‹โ€‹of n

    typea

Take as an example

replicateA :: Int -> [Char]   -- r = Int , a = Char
replicateA 0 = []
replicateA n = 'A' : replicate (n-1)

      

By comparison, the type is [r -> a]

roughly the following:

  • Print a natural number n

    (including infinite)
  • In each of the n

    list items :
    • Make an input like r

    • Output type value a

The key fact here is that the length of the list must be prepared before you know the input r

. This cannot be done, in general, since the length may depend on r

, as the above example shows replicateA

.

+1


source







All Articles