且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将类型作为参数传递给Haskell中的函数?

更新时间:2023-01-10 15:07:44

Haskell支持高度的多态性。特别是

  readAny n stream = foldl next([],stream)[1..n] 
其中
next(lst,x:xs)_ =(lst ++ [v],xs)
where
v = read x


有类型

  readAny ::(Enum b,Num b,阅读a)=> b  - > [字符串]  - > ([a],[String])

因此

  readInts ::(Enum b,Num b,Read a)=> [字符串]  - > ([Int],[String])
readInts = readAny

readFloats ::(Enum b,Num b,Read a)=> [字符串] - > ([Float],[String])
readFloats = readAny

你不需要专门方式。 Haskell会自动推断出最普​​通的类型,这里的 readAny 会做你想要的。



不可能在Haskell中传入类型作为参数。你很少会需要。对于那些需要的情况,您可以通过传递一个具有所需类型的值来模拟行为。

Haskell具有返回类型多态性,所以您真的不应该担心通过类型 - 可能性是功能将做你想要的东西,而你告诉他们。


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

readAny n stream = foldl next ([], stream) [1..n]
  where
    next (lst, x:xs) _ = (lst ++ [v], xs)
      where
        v = read x 

has type

readAny :: (Enum b, Num b, Read a) => b -> [String] -> ([a], [String])

thus

readInts :: (Enum b, Num b, Read a) => [String] -> ([Int], [String])
readInts = readAny

readFloats :: (Enum b, Num b, Read a) => [String] -> ([Float], [String])
readFloats = readAny

you dont need to specialize the type. Haskell will automatically infer the most general type possible, and the readAny here 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.