0

Suppose I want to define a function f in terms of some other predefined function g as follows:

f :: Int -> Int -> Int
f 2 b = g b
f _ _ = 1

That is, I want to define the projection, f(2,_) : Int->Int to be the same as g(_) : Int->Int. Gladly, Haskell has first class functions, and so definitions like the following squarePlusOne are valid and standard:

plusOne :: Int -> Int
plusOne i = i+1
square :: Int -> Int
square i = i*i
squarePlusOne :: Int -> Int
squarePlusOne = plusOne . Square

With Haskell's currying (ie. f takes just one Int as input and returns an (Int->Int) typed function), I am surprised I cannot write

f 2 = g

Why not? Or is there some other syntax?

Owen
  • 448
  • 3
  • 11

2 Answers2

4

Indeed, writing f 2 = g is a valid way to define f. However, when defining functions in this way, remember you must define the whole function with the same pattern signature. That is, you may not exhaust your function by writing

f 2 = g
f i j = i+j

Instead, this may be achieved like so:

f 2 = g
f i = (\j-> i+j)
Owen
  • 448
  • 3
  • 11
2

You can use the const function, which creates a function that ignores its argument to return a fixed value.

f :: Int -> Int -> Int
f 2 = g            -- f 2 x = g x
f _ = const 1      -- f _ x = const 1 x == (\_ -> 1) x == 1
chepner
  • 497,756
  • 71
  • 530
  • 681