Haskell: Create a list of tuples from a tuple with a static element and a list -
need create list of tuples tuple static element , list. such as:
(int, [string]) -> [(int, string)] feel should simple map call having trouble getting output tuple zip need list input, not constant.
i think direct , easy understand solution (you seem acquainted map anyway):
f :: (int, [string]) -> [(int, string)] f (i, xs) = map (\x -> (i, x)) xs (which happens desugared version of [(i, x) | x < xs], landei proposed)
then
prelude> f (3, ["a", "b", "c"]) [(3,"a"),(3,"b"),(3,"c")] this solution uses pattern matching "unpack" tuple argument, first tuple element i , second element xs. simple map on elements of xs convert each element x tuple (i, x), think you're after. without pattern matching more verbose:
f pair = let = fst pair -- first element xs = snd pair -- second element in map (\x -> (i, x)) xs furthermore:
the algorithm no way specific (int, [string]), can safely generalize function replacing int , string type parameters a , b:
f :: (a, [b]) -> [(a, b)] f (i, xs) = map (\x -> (i, x)) xs this way can do
prelude> f (true, [1.2, 2.3, 3.4]) [(true,1.2),(true,2.3),(true,3.4)] and of course if rid of type annotation altogether, type (a, [b]) -> [(a, b)] type haskell infers (only different names):
prelude> let f (i, xs) = map (\x -> (i, x)) xs prelude> :t f f :: (t, [t1]) -> [(t, t1)] bonus: can shorten \x -> (i, x) (i,) using tuplesections language extension:
{-# language tuplesections #-} f :: (a, [b]) -> [(a, b)] f (i, xs) = map (i,) xs also, Ørjan johansen has pointed out, function sequence indeed generalize further, mechanisms thereof bit beyond scope.
Comments
Post a Comment