다음은 단순한 예제이며, 너무 많이 반복하지 않고 간단한 함수를 작성하는 데 문제가 있습니다. 필자가 작성하려고하는 실제 프로그램은 파이썬에서 BI 서버를위한 메모리 내 데이터베이스의 포트입니다. 실제로 Vector A와 같은 다형성 유형에서 작동하는 함수로 표현할 수있는 더 많은 다른 유형 (약 8 개)과 훨씬 더 많은 논리가 있지만 여전히 일부 논리는 다른 유형의 값을 처리해야합니다.기본 유형의 유한 도메인 컨테이너에 대한 동적 타이핑
[(Int, WrappedValue)] type을 사용하여 각 값을 분리하여 배치하는 것은 효율성상의 이유로 인해 옵션이 아닙니다. 실제 코드에서는 언 박싱 벡터를 사용하고 있습니다.
type Vector a = [(Int, a)] -- always sorted by fst
data WrappedVector = -- in fact there are 8 of them
FloatVector (Vector Float)
| IntVector (Vector Int)
deriving (Eq, Show)
query :: [WrappedVector] -> [WrappedVector] -- equal length
query vectors = map (filterIndexW commonIndices) vectors
where
commonIndices = intersection [mapFstW vector | vector <- vectors]
intersection :: [[Int]] -> [Int]
intersection = head -- dummy impl. (intersection of sorted vectors)
filterIndex :: Eq a => [Int] -> Vector a -> Vector a
filterIndex indices vector = -- sample inefficient implementation
filter (\(idx, _) -> idx `elem` indices) vector
mapFst :: Vector a -> [Int]
mapFst = map fst
-- idealy I whould stop here, but I must write repeat for all possible types
-- and kinds of wrapped containers and function this:
filterIndexW :: [Int] -> WrappedVector -> WrappedVector
filterIndexW indices vw = case vw of
FloatVector v -> FloatVector $ filterIndex indices v
IntVector v -> IntVector $ filterIndex indices v
mapFstW :: WrappedVector -> [Int]
mapFstW vw = case vw of
FloatVector v -> map fst v
IntVector v -> map fst v
-- sample usage of query
main = putStrLn $ show $ query [FloatVector [(1, 12), (2, -2)],
IntVector [(2, 17), (3, -10)]]
mapFstW 및 filterIndexW 함수처럼 래핑 및 래핑을 사용하지 않고 이러한 코드를 어떻게 표현할 수 있습니까? 그것은 단지 형 수준에서 차이를 만들기 때문에
이 문제는 실제 문제에 잘 맞습니다 (Data.Typeable의 도움으로). 감사합니다. –
다행스럽게도 도움이되었습니다. –