Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement this function without using mixed lists?

Let's say I have a function that takes a list of function-list pairs, and maps the function in each pair onto the list in the pair, for example:

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

Is there a way of implementing myFunction so that the code I provided above will work as is without any modifications?

My problem is I can't figure out how to implement myFunction because the types of each sub-list could 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 will convert its list into a list of strings (so the final list will have type [[Char]]), but I don't know how to express this in Haskell.

like image 442
John Walters Avatar asked Sep 01 '26 10:09

John Walters


1 Answers

You can do it with existential types

{-# LANGUAGE ExistentialQuantification #-}

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

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

And run it as:

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

main = print $ map apply table
like image 87
Don Stewart Avatar answered Sep 03 '26 23:09

Don Stewart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!