Jorgel
Jorgel

Reputation: 930

Where in a "block"

I am doing a program that have very similar code blocks, and I was trying to make a where in a "block". Just an example

function "sum" x = x + a
function "product" x = x * a
  where 
    a = 2

I want the 'a' to be replaced in both lines, but I didn't find out if this is possible using where

Thanks in advance

Upvotes: 0

Views: 155

Answers (4)

Julian.zhang
Julian.zhang

Reputation: 719

I think you can define a new function geta

geta=2

And then you can use the geta function in any other functions.

I don't think mix every functions is a good way, maybe you will have 20 functions need the same value

Upvotes: 0

amindfv
amindfv

Reputation: 8448

You can also introduce a second function:

function fName x = function' fName x
   where
      a = 2
      function' "sum"     x = x + a
      function' "product" x = x * a 

Upvotes: 3

Ingo
Ingo

Reputation: 36329

If you really need this, you need to merge the two function clauses. One way to do this:

func what x = case what of
        "add" -> x+a
        "mul" -> x*a
    where
       a = 2

Upvotes: 7

Daniel Kaplan
Daniel Kaplan

Reputation: 67300

(Forgive me because I'm a newbie.) I don't think this is possible. The scope of the where "block" is the function it's defined in. What you can do is this, though:

Prelude> let a = 2
Prelude> let sum x = x + a
Prelude> let product x = x * a
Prelude> sum 3
5

This is done in GHCi. You may be concerned that everyone can see a, but if this were in a .hs file, you could make it a module and just not export a, and then only these functions could see it.

Upvotes: 0

Related Questions