您好,欢迎光临本网站![请登录][注册会员]  
文件名称: Maybe.Haskell.pdf
  所属分类: 讲义
  开发工具:
  文件大小: 320kb
  下载次数: 0
  上传时间: 2019-07-05
  提 供 者: weixin_********
 详细说明:我不想教你Haskell. 我不会描述如何设置Haskell编程环境,也不会向您展示如何编写和运行完整的Haskell程序,或者深入研究. 相反,我希望展示其“学术”理念,这些想法直接导致更干净、更易于维护的代码,从而解决实际问题。Contents Introduction AnA| ternate so|utⅰon Required Experience Structure What this book is not Haskell basics Our Own Data Types Pattern Matching 6 Sum T Kinds and parameters 8 Maybe Don't Give Up 12 Functor 14 Choices 5 Discovering a functor 16 About Type Classes 17 CONTENTS Functor 18 The functor laws Why Is this Useful? 24 Curried form 25 Recap 29 Applicative Hiding Details Follow The Types 32 pply 33 Chaining 35 Applicative In the Wild Monad More power 40 And then? 40 Bind 42 Chainin 42 Do Notation ing u 46 ther Types 48 List 55 What's Next Introduction As a programmer, I spend a lot of time dealing with the fallout from one specific problem: partial functions. A partial function is one that can't provide a valid result or all possible inputs. If you write a function (or method ) to return the first ele ment in an array that satisfies some condition, what do you do if no such element from raising an exception, what can you do?ol exists? You've been given an input for which you can't return a valid result. Aside The most popular way to to deal with this is to return a special value that indicates failure. Ruby has nil, Java has null, and many c functions return -1 in failure cases This is a huge hassle. You now have a system in which any value at any time can either be the value you expect or nil, always If you try to find a user and you get back a value and you try to treat it like a User then it's actually nil, you get a NoMethodError. What's worse, that error may not happen anywhere near the source of the problem. the line of code that created that nil may not even appear in the eventual backtrace. The result is various"nil checks" peppered throughout the code. Is this the best we can do? The problem of partial functions is not going away. User input may be invalid, files may not exist, networks may fail. We will always need a way to deal with partial functions What we don t need is null An Alternate Solution In languages with sufficiently-expressive type systems, we have another option we can state in the types that certain values may not be present. Functions nor INTRODUCTION mally written in a partial way can instead return a type that captures any potentia non-presence. Not only does it make it explicit and "type checked"that when a value may not be present, you have code to handle that case, but it also means that if a value is not of this special"nullable"type, you can feel safe in your assump tion that the value' s really there- no nil-checks required The focus of this book will be haskells implementation of this idea via the maybe data type. This type and all of the functions that deal with it are not built-in, anguage -level constructs. All of it is implemented as libraries, written in a very straightforward way. In fact, we'l write most of that code ourselves over the course of this short book Haskell is not the only language to have such a construct. For example, Scala has a similar Option type and Swift has Optional with various built-in syntax elements to make its usage more convenient. Many of the ideas implemented in these lan- guages were lifted directly from Haskell. If you happen to use one of them, it can be good to learn where the ideas originated Required Experience I'll assume no prior haskell experience. i expect that those reading this book will have programmed in other, more traditional languages, but I'll also ask that you actively combat your prior programming experience For example you're going to see code like this countEvens length. filter even This is a function definition written in an entirely different style than you may be used to. Even so, I'll bet you can guess what it does, and even get close to how it does it: filter even probably takes a list and filters it for only even elements length probably takes a list and returns the number of elements it has Given those fairly obvious facts, you might guess that putting two things together with()must mean you do one and then give the result to the other. That makes this expression a function which must take a list and return the number of even elements it has. Without mentioning any actual argument, we can directly assign INTRODUCTION this function the name countEvens. There's no need in Haskell to say that count evens of some x is to take the length after filtering for the even values of that x. We can state directly that count-evens is taking the length after filtering for evens This is a relatively contrived example but it's indicative of the confusion that can happen at any level: if your first reaction is"such weird syntax! What is this crazy dot thing!? " you're going to have a bad time. Instead, try to internalize the parts that make sense while getting comfortable with not knowing the parts that don't s you learn more, the various bits will tie together in ways you might not expect Structure We'll spend this entire book focused on a single type constructor called Maybe. We'll start by quickly covering the basics of Haskell, but only so far that we see the op portunity for such a type and can't help but invent it ourselves. With that defined, ll quickly see that it's cumbersome to use. This is because Haskell has taken an inherently cumbersome concept and put it right in front of us by naming it and requiring we deal with it at every step From there, we 'll explore three type classes whose presence will make our lives far less cumbersome. We'll see that Maybe has all of the properties required to call it a functor, an applicative functor, and even a monad. These terms may sound scary, but we'll go through them slowly, each concept building on the last. These three interfaces are crucial to how i/o is handled in a purely functional language such as Haskell. Understanding them will open your eyes to a whole new world of abstractions and demystify notoriously opaque topics Finally, with a firm grasp on how these concepts operate in the context of Maybe, we 'll discuss other types which share these qualities. This is to reinforce the fact that these ideas are abstractions. They can be applied to any type that meets cer tain criteria. Ideas like functor and monad are not specifically tied to the concept of partial functions or nullable values. They apply broadly to things like lists, trees, exceptions, and program evaluation INTRODUCTION What This book is not don't intend to teach you haskell. Rather, I chow you barely enough Haskell so that I can wade into more interesting topics. I want to show how this Maybe data type can add safety to your code base while remaining convenient, ex pressive, and powerful. My hope is to show that Haskell and its"academic"ideas are not limited to Phd thesis papers. These ideas result directly in cleaner, more maintainable code that solves practical problems I won,'t describe how to set up a Haskell programming environment, show you how to write and run complete Haskell programs, or dive deeply into every lan guage construct we 'll see. If you are interested in going further and actually learn ing Haskell (and I hope you are! ), then I recommend following Chris Allen's great learning path Lastly, a word of general advice before you get started The type system is not your enemy, it's your friend. It doesn't slow you down, it keeps you honest. Keep an open mind. Haskell is simpler than you think Monads are not some mystical burrito, they're a simple abstraction which, when applied to a variety of problems, can lead to elegant solutions. Don't get bogged down in That you don't understand, dig deeper into what you do. and above all, take your time Haskell basics When we declare a function in Haskell, we first write a type signature five:: Int We can read this as five of type Int Next. we write a definition five =5 We can read this as five is 5 In Haskell, is not variable assignment, it's defining equivalence. We're saying here that the word five is equivalent to the literal 5. Anywhere you see one, you can replace it with the other and the program will always give the same answer. This property is called referential transparency and it holds true for any Haskell definition, no matter how complicated It's also possible to specify types with an annotation rather than a signature. We can annotate any expression with: to explicitly tell the compiler the type we want(or expect) that expression to have lmostThird =(3:: Float)/9 >0.3333334 actualThird =(3: Rational)/9 >1%3 CHAPTER 1. HASKELL BASICS We can read these as almostThird is 3, of type Float, divided by 9 and actualThird is 3, of type Rational, divided by 9 Type annotations and signatures are usually optional, as Haskell can almost always tell the type of an expression by inspecting the types of its constituent parts or seeing how it is eventually used. This process is called type inference. For example, Haskell knows that actualthird is a rational because it saw that 3 is a rational Since you can only use (/)with arguments of the same type, it enforced that 9 is also a Rational. Knowing that (/)returns the same type as its arguments, the fina result of the division must itself be a rational Good Haskellers will include a type signature on all top-level definitions anyway. It provides executable documentation and may, in some cases, prevent errors which occur when the compiler assigns a more generic type than you might otherwise Arguments Defining functions that take arguments looks like this add Int - Int add x The type signature can be confusing because the argument types are not sepa rated from the return type. There is a good reason for this, but I won't go into it yet. For now, feel free to mentally treat the thing after the last arrow as the return ype After the type signature, we give the function s name(add)and names for any ar- guments it takes(x and y). On the other side of the = we define an expression using those names Higher-order functions Functions can take and return other functions. These are known as higher-order functions. In type signatures, any function arguments or return values must be surrounded by parentheses
(系统自动生成,下载前可以参看下载内容)

下载文件列表

相关说明

  • 本站资源为会员上传分享交流与学习,如有侵犯您的权益,请联系我们删除.
  • 本站是交换下载平台,提供交流渠道,下载内容来自于网络,除下载问题外,其它问题请自行百度
  • 本站已设置防盗链,请勿用迅雷、QQ旋风等多线程下载软件下载资源,下载后用WinRAR最新版进行解压.
  • 如果您发现内容无法下载,请稍后再次尝试;或者到消费记录里找到下载记录反馈给我们.
  • 下载后发现下载的内容跟说明不相乎,请到消费记录里找到下载记录反馈给我们,经确认后退回积分.
  • 如下载前有疑问,可以通过点击"提供者"的名字,查看对方的联系方式,联系对方咨询.
 相关搜索: Maybe.Haskell.pdf
 输入关键字,在本站1000多万海量源码库中尽情搜索: