The following two functions are extremely similar. They read from a [String] n elements, either [Int] or [Float]. How can I factor the common code out? I don’t know of any mechanism in Haskell that supports passing types as arguments.
readInts n stream = foldl next ([], stream) [1..n]
where
next (lst, x:xs) _ = (lst ++ [v], xs)
where
v = read x :: Int
readFloats n stream = foldl next ([], stream) [1..n]
where
next (lst, x:xs) _ = (lst ++ [v], xs)
where
v = read x :: Float
I am at a beginner level of Haskell, so any comments on my code are welcome.
Haskell supports a high degree of polymorphism. In particular
has type
thus
you dont need to specialize the type. Haskell will automatically infer the most general type possible, and the
readAnyhere will do what you want.It is not possible to pass types as arguments in Haskell. Rarely would you need to. For those few cases where it is necessary you can simulate the behavior by passing a value with the desired type.
Haskell has “return type polymorphism” so you really shouldn’t worry about “passing the type”–odds are that functions will do what you want without you telling them to.