where を使って計算の中間結果に名前をつけることが出来る。
ただしwhere にはスコープがあり、その関数の中でしか見えないため、注意すること。
bmiTell'' :: Double -> Double -> String bmiTell'' weight height | bmi <= 18.5 = "You're underweight" | bmi <= 25.0 = "You're normal" | bmi <= 30.0 = "You're fat" | otherwise = "You're a whale" where bmi = weight / height ^ 2 bmiTell''' :: Double -> Double -> String bmiTell''' weight height | bmi <= 18.5 = "You're underweight" | bmi <= 25.0 = "You're normal" | bmi <= 30.0 = "You're fat" | otherwise = "You're a whale" where bmi = weight / height ^ 2 skinny = 18.5 normal = 25.0 fat = 30.0 --関数の外からwhere を使おうとしているため、エラーが返る -- greet :: String -> String -- greet "Juan" = niceGreeting ++ " Juan" -- greet "Fernando" = niceGreeting ++ "Fernando" -- greet name = badGreeting ++ " " ++ name -- where niceGreeting = "Hello, " -- badGreeting = "Oh! Pfft." badGreeting :: String badGreeting = "Pfft " niceGreeting :: String niceGreeting = "Hello, " greet :: String -> String greet "Juan" = niceGreeting ++ " Juan" greet "Fernando" = niceGreeting ++ " Fernando" greet name = badGreeting ++ " " ++ name initials :: String -> String -> String initials firstname lastname = [f] ++ ". " ++ [l] ++ "." where (f:_) = firstname (l:_) = lastname calcBmis :: [(Double, Double)] -> [Double] calcBmis xs = [bmi w h | (w, h) <- xs] where bmi weight height = weight / height ^ 2
結果
Main> bmiTell'' 85 1.90 "You're normal" Main> bmiTell''' 85 1.90 "You're normal" Main> greet "Juan" "Hello, Juan" Main> greet "Fernando" "Hello, Fernando" Main> let name = "Hoge" Main> greet name "Pfft Hoge" Main> initials "Michael" "Kheel" "M. K." Main> calcBmis [(85.0,1.90)] [23.545706371191137]