Where Clause Applied To Multiple Patterns

梦想的初衷 提交于 2019-12-07 11:11:04

问题


I have a function with multiple patterns. I have two or more of them which share the same expression which I want to replace. Now if I write a where clause at the bottom, indent it and define a new variable as the expression I wanted to replace it won't work.

Example:

myFunction firstParam secondParam = expression
myFunction firstParam _ = 1 + expression
    where expression = firstParam + secondParam

Compiler message:

Not in scope: `expression'
Not in scope: `secondParam'

How do I do it?


回答1:


You can factor out the pattern matches into a case. For example:

myFunction :: Int -> Int -> Int
myFunction a b = case (a, b) of
  (0, 4) -> x
  (_, b) -> x + b
  where
    x = a + b

Here x is visible in both case branches.



来源:https://stackoverflow.com/questions/27961795/where-clause-applied-to-multiple-patterns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!