Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Haskell
Wiki community
Recent changes
Random page
HaskellWiki
Search
Search
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
10分で学ぶHaskell
(section)
Page
Discussion
English
Read
Edit
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Special pages
Page information
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== [[関数]]定義 == <hask>main</hask>と呼ばれる[[Introduction to Haskell IO/Actions |IO action]]の定義について先に触れました。 <haskell> main = do putStrLn "What is 2 + 2?" x <- readLn if x == 4 then putStrLn "You're right!" else putStrLn "You're wrong!" </haskell> では次に、実際に<hask>factorial</hask>という関数の ''[[関数]]" 定義を書いてみることで、上の例を補ってみましょう。丁寧に書こうと思うので、モジュールヘッダも追加します。 <haskell> module Main where factorial n = if n == 0 then 1 else n * factorial (n - 1) main = do putStrLn "What is 5! ?" x <- readLn if x == factorial 5 then putStrLn "You're right!" else putStrLn "You're wrong!" </haskell> <tt>ghc --make Test.hs</tt>と入力し再ビルドします。そして実行します。 $ ./Test What is 5! ? 120 You're right! 階数が得られました。ビルトイン関数のように、<hask>factorial 5</hask>と括弧なしで関数が呼び出せました。 今度は<tt>ghci</tt>を使って[[型]]を調べてみましょう。 $ ghci Test.hs << GHCi banner >> Ok, modules loaded: Main. Prelude Main> :t <hask>factorial</hask> <hask>factorial :: (Num a) => a -> a</hask> 関数の型は引数の型とともに表され、その後に<hask> -> </hask>が来て結果の型が書かれます。(結果も型クラス<hask>Num</hask>となります) 階数は場合分けを使うことで簡単にできます。 <haskell> factorial 0 = 1 factorial n = n * factorial (n - 1) </haskell>
Summary:
Please note that all contributions to HaskellWiki are considered to be released under simple permissive license (see
HaskellWiki:Copyrights
for details). If you don't want your writing to be edited mercilessly and redistributed at will, then don't submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource.
DO NOT SUBMIT COPYRIGHTED WORK WITHOUT PERMISSION!
Cancel
Editing help
(opens in new window)
Toggle limited content width