redfish64
redfish64

Reputation: 575

How to reference the type from a function inside a sub function

Is it possible to reference the type from a function's definition within one of the sub-functions within it? (See comments in code below for more detail)

module TypesAndSubFunctions where

class DingBat k where

foo :: DingBat k => k -> String
foo kv = "foo"
  where
    -- how can I define bar so that the type 'k2' is the same 
    -- as k from foo? Or is this not possible?
    --
    -- The following causes an error, because k2 isn't the same type
    -- as foo's k. But I can't seem to find a way to reference foo's k
    -- without specifying it as an arg (as I do in bar2). Is this just
    -- the way haskell is?
    --
    -- I would think there should be a simple way to reference k from
    -- foo with the type definition of bar, but I can't see how.
    -- bar :: DingBat k2 => k2 -> String
    -- bar kv2 = ding2 kv kv2

    -- To restate the problem, I would like the same functionality for
    -- bar as bar2, below, but without having to specify the first arg
    bar2 :: DingBat k => k -> k -> String
    bar2 kv kv2 = ding2 kv kv2

ding2 :: DingBat k => k -> k -> String
ding2 = undefined

Upvotes: 2

Views: 65

Answers (1)

chi
chi

Reputation: 116174

This should do the job. To reuse k you need to turn on a very common extension.

{-# LANGUAGE ScopedTypeVariables #-}

foo :: forall k . DingBat k => k -> String
foo kv = "foo"
  where
  bar :: k -> String
  bar kv2 = ding2 kv kv2

Upvotes: 2

Related Questions