How to implement this function without using mixed lists?

Let's say I have a function that takes a list of pairs of a list of functions and matches a function in each pair in a list in a pair, for example:

myFunction [("SOME"++,["DAY","ONE"]), (show,[1,2])] == [["SOMEDAY", "SOMEONE"],["1","2"]]

Is there a way to implement myFunction so that the code above works without changes?

My problem is that I cannot figure out how to implement myFunction because the types of each sub-list can be different (in my example, I have a list of strings ["DAY", ONE "] and a list of numbers: [1, 2]). I know that each function in the list converts its list to a list of strings (so the final list will be of type [[Char]]), but I don’t know how to express this in Haskell.

+3
source share
2 answers

{-# LANGUAGE ExistentialQuantification #-}

data T = forall a b. Show b => (:?:) (a -> b) [a]

table =
    [ ("SOME"++) :?: ["DAY","ONE"]
    , (show)     :?: [1,2]
    , (+1)       :?: [2.9, pi]
    ]

:

apply :: T -> String
apply (f :?: xs) = show $ map f xs

main = print $ map apply table
+4

, , , Show. :

{-# LANGUAGE ExistentialQuantification #-}

data S = forall a. Show a => S a

instance Show S where
    show (S s) = show s

f :: [S] -> [String]
f xs = map show xs

ghci:

*Main> f [S 1, S True, S 'c']
["1","True","'c'"]

, , Haskell. ( , ) ( , , ).

+1

All Articles