Haskell: Where vs. Let

前端 未结 5 1673
余生分开走
余生分开走 2020-12-02 04:56

I am new to Haskell and I am very confused by Where vs. Let. They both seem to provide a similar purpose. I have read a few comparisons bet

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 05:11

    Sadly, most of the answers here are too technical for a beginner.

    LHYFGG has a relevant chapter on it -which you should read if you haven't already, but in essence:

    • where is just a syntactic construct (not a sugar) that are useful only at function definitions.
    • let ... in is an expression itself, thus you can use them wherever you can put an expression. Being an expression itself, it cannot be used for binding things for guards.

    Lastly, you can use let in list comprehensions too:

    calcBmis :: (RealFloat a) => [(a, a)] -> [a]
    calcBmis xs = [bmi | (w, h) <- xs, let bmi = w / h ^ 2, bmi >= 25.0]
    -- w: width
    -- h: height
    

    We include a let inside a list comprehension much like we would a predicate, only it doesn't filter the list, it only binds to names. The names defined in a let inside a list comprehension are visible to the output function (the part before the |) and all predicates and sections that come after of the binding. So we could make our function return only the BMIs of people >= 25:

提交回复
热议问题