How to define function signatures partially in Haskell?

后端 未结 6 1206
刺人心
刺人心 2021-02-03 17:54

Starting point:

fn :: [a] -> Int
fn = (2 *) . length

Let\'s say we only want to constrain the return value, then we could write:

6条回答
  •  长发绾君心
    2021-02-03 18:12

    I've been looking for a way to say 'x's type unifies with T'. The solutions given by Will Ness and chi are close to what I came up with, but there is a way to do it in Haskell 98, without butchering your own function.

    -- Your function, without type signature.
    fn = (2 *) . length
    
    -- The type signature, without actual definition.
    fnTy :: [Char] -> a
    fnTy = undefined
    
    -- If this type checks, then the type of 'fn' can be unified 
    --                                      with the type of 'fnTy'.
    fn_unifies_with_type :: ()
    fn_unifies_with_type = let _ = fn `asTypeOf` fnTy in ()
    

    You could even go for just

    fn = (2 *) . length
      where
        _ = fn `asTypeOf` (undefined :: [Char] -> a)
    

提交回复
热议问题