Return specific type within Haskell

前端 未结 3 2048
我寻月下人不归
我寻月下人不归 2020-12-01 14:36

I have a pretty general question about Haskell\'s type system. I\'m trying to become familiar with it, and I have the following function:

getN :: Num a =>         


        
3条回答
  •  天涯浪人
    2020-12-01 15:08

    Check out Existentially quantified types.

    One way to solve it would be to define a new data type

    data NumBox = forall n. Num n => NumBox n
    

    You'll need -XExistentialQuantification to get this to work.

    Now you can write something like

    getN :: NumBox
    getN = NumBox (5.0 :: Double)
    

    You can also define a NumBox-list as

    let n3 = [NumBox (4.0 :: Double), NumBox (1 :: Integer), NumBox (1 :: Int) ]
    

提交回复
热议问题