Programming Languages A(Coursera / University of Washington) Assignment 2

原文件已上传到GitHub: 点这里
分数是80分(刚好通过)(用了一点限制函数)

第二次作业,主要是练习 pattern match
这真是很棒的feature,能够很好的控制scope,达到closure效果
也能领会ml的 referential transparency、lazy evaluation、statically typed 等 feature
在和别人交流的过程中,还学到了guard,存在ocaml,F#中的一种特性,但是sml没有,所以sml不内置支持range match 如下图所示

在这里插入图片描述

函数签名

第二次作业非challenge部分是写11个函数
分别是

val all_except_option = fn : string * string list -> string list option
val get_substitutions1 = fn : string list list * string -> string list
val get_substitutions2 = fn : string list list * string -> string list
val similar_names = fn : string list list * {first:string, last:string, middle:string}
-> {first:string, last:string, middle:string} list
val card_color = fn : card -> color
val card_value = fn : card -> int
val remove_card = fn : card list * card * exn -> card list
val all_same_color = fn : card list -> bool
val sum_cards = fn : card list -> int
val score = fn : card list * int -> int
val officiate = fn : card list * move list * int -> int

第一题

This problem involves using first-name substitutions to come up with alternate names. For example,
Fredrick William Smith could also be Fred William Smith or Freddie William Smith. Only part (d) is
specifically about this, but the other problems are helpful.
(a) Write a function all_except_option, which takes a string and a string list. Return NONE if the
string is not in the list, else return SOME lst where lst is identical to the argument list except the string
is not in it. You may assume the string is in the list at most once. Use same_string, provided to you,
to compare strings. Sample solution is around 8 lines.
(b) Write a function get_substitutions1, which takes a string list list (a list of list of strings, the
substitutions) and a string s and returns a string list. The result has all the strings that are in
some list in substitutions that also has s, but s itself should not be in the result. Example:
get_substitutions1([["Fred","Fredrick"],["Elizabeth","Betty"],["Freddie","Fred","F"]],
"Fred")
(* answer: ["Fredrick","Freddie","F"] *)
Assume each list in substitutions has no repeats. The result will have repeats if s and another string are
both in more than one list in substitutions. Example:
get_substitutions1([["Fred","Fredrick"],["Jeff","Jeffrey"],["Geoff","Jeff","Jeffrey"]],
"Jeff")
(* answer: ["Jeffrey","Geoff","Jeffrey"] *)
Use part (a) and ML’s list-append (@) but no other helper functions. Sample solution is around 6 lines.
(c) Write a function get_substitutions2, which is like get_substitutions1 except it uses a tail-recursive
local helper function.
(d) Write a function similar_names, which takes a string list list of substitutions (as in parts (b) and
(c)) and a full name of type {first:string,middle:string,last:string} and returns a list of full
names (type {first:string,middle:string,last:string} list). The result is all the full names you
can produce by substituting for the first name (and only the first name) using substitutions and parts (b)
or (c). The answer should begin with the original name (then have 0 or more other names). Example:
similar_names([["Fred","Fredrick"],["Elizabeth","Betty"],["Freddie","Fred","F"]],
{first="Fred", middle="W", last="Smith"})
(* answer: [{first="Fred", last="Smith", middle="W"},
{first="Fredrick", last="Smith", middle="W"},
{first="Freddie", last="Smith", middle="W"},
{first="F", last="Smith", middle="W"}] *)
Do not eliminate duplicates from the answer. Hint: Use a local helper function. Sample solution is
around 10 lines.

(*1.a*)
fun all_except_option(str,xs) =
    case xs of
	[] => NONE
      | y::ys' => if same_string(str,y) then
		      if null ys'
		      then
			    SOME []
		      else
		          SOME ys'
		  else
		      case all_except_option(str,ys') of
			  NONE => NONE
			 |_  => let val tmp = all_except_option(str,ys')
			  in
			      SOME (y::(valOf tmp))
			  end
				    
				   
(*1.b*)
fun get_substitutions1(li:(string list)list,s) =
    case li of
	[] => []
      | y::ys' =>let val tmp = all_except_option(s,y)
		 in
		     if isSome tmp
		     then (valOf tmp)@get_substitutions1(ys',s)
		     else []@get_substitutions1(ys',s)
		 end 
		     

(*1.c It's a trade-off*)
fun get_substitutions2(lli:(string list)list,ss:string) =
    let fun helper(li,s)=
	case li of
		      [] => (tl s)
		    | y::ys' => let val tmp = all_except_option(hd s,y)
				in
				    if isSome tmp
				    then helper(ys',s@(valOf tmp))
				    else helper(ys',s)
				end
				    
     in
	 helper(lli,[ss])
     end

				    
				  
		      
(*1.d *)
 (*
    val similar_names = fn : string list list * {first:string, last:string, middle:string}-> {first:string, last:string, middle:string} list
 *)

fun similar_names(li,s:{first:string, last:string, middle:string})=
    let fun fix(xs,s:{first:string, last:string, middle:string}) =
	    case xs of
		[] => []
	      | x::xs' => [case s of {first=_,last=b,middle=c}=>{first=x,last=b,middle=c}]@fix(xs',s)
    in
	[s]@fix(get_substitutions1(li,(case s of {first=a,last=_,middle=_}=>a)),s)
    end
	

(*
card_color = fn : card -> color
card_value = fn : card -> int
remove_card = fn : card list * card * exn -> card list
all_same_color = fn : card list -> bool
sum_cards = fn : card list -> int
score = fn : card list * int -> int
officiate = fn : card list * move list * int -> int
*)

第二题

This problem involves a solitaire card game invented just for this question. You will write a program that
tracks the progress of a game; writing a game player is a challenge problem. You can do parts (a){(e) before
understanding the game if you wish.
A game is played with a card-list and a goal. The player has a list of held-cards, initially empty. The player
makes a move by either drawing, which means removing the first card in the card-list from the card-list and
adding it to the held-cards, or discarding, which means choosing one of the held-cards to remove. The game
ends either when the player chooses to make no more moves or when the sum of the values of the held-cards
is greater than the goal.
The objective is to end the game with a low score (0 is best). Scoring works as follows: Let sum be the sum
of the values of the held-cards. If sum is greater than goal, the preliminary score is three times (sum−goal),
else the preliminary score is (goal − sum). The score is the preliminary score unless all the held-cards are
the same color, in which case the score is the preliminary score divided by 2 (and rounded down as usual
with integer division; use ML’s div operator).
(a) Write a function card_color, which takes a card and returns its color (spades and clubs are black,
diamonds and hearts are red). Note: One case-expression is enough.
(b) Write a function card_value, which takes a card and returns its value (numbered cards have their
number as the value, aces are 11, everything else is 10). Note: One case-expression is enough.
(c) Write a function remove_card, which takes a list of cards cs, a card c, and an exception e. It returns a
list that has all the elements of cs except c. If c is in the list more than once, remove only the first one.
If c is not in the list, raise the exception e. You can compare cards with =.
(d) Write a function all_same_color, which takes a list of cards and returns true if all the cards in the
list are the same color. Hint: An elegant solution is very similar to one of the functions using nested
pattern-matching in the lectures.
(e) Write a function sum_cards, which takes a list of cards and returns the sum of their values. Use a locally
defined helper function that is tail recursive. (Take \calls use a constant amount of stack space" as a
requirement for this problem.)
(f) Write a function score, which takes a card list (the held-cards) and an int (the goal) and computes
the score as described above.
(g) Write a function officiate, which \runs a game." It takes a card list (the card-list) a move list
(what the player \does" at each point), and an int (the goal) and returns the score at the end of the
game after processing (some or all of) the moves in the move list in order. Use a locally defined recursive
helper function that takes several arguments that together represent the current state of the game. As
described above:
• The game starts with the held-cards being the empty list.
• The game ends if there are no more moves. (The player chose to stop since the move list is empty.)
• If the player discards some card c, play continues (i.e., make a recursive call) with the held-cards
not having c and the card-list unchanged. If c is not in the held-cards, raise the IllegalMove
exception.
• If the player draws and the card-list is (already) empty, the game is over. Else if drawing causes
the sum of the held-cards to exceed the goal, the game is over (after drawing). Else play continues
with a larger held-cards and a smaller card-list.
Sample solution for (g) is under 20 lines.



(*2.a*)
	
fun card_color(cd:card) =
    case cd of
	(Spades,_) => Black
      | (Clubs,_) => Black
      | (Diamonds,_) => Red
      | (Hearts,_) => Red

(*2.b*)
(*	card_value = fn : card -> int	*)	  
fun card_value(cd:card):int =
    case cd of
	(_,Num(a)) => a
     | (_,Ace) => 11
     | (_,_) => 10

(*2.c*)
		     
fun remove_card(xs:card list,c,e)=
    let fun check(xs:card list,c)=
	    case xs of
		[] => false
	      | y::ys' => if y=c then true
			  else check(ys',c);
	fun getValue(xs:card list,c)=
	    case xs of
		[] => []
	      | y::ys' => if y=c then ys'
  
			  else
			      y::getValue(ys',c)
    in
	let val flag = check(xs,c)
	in
	    if false=flag then
		raise e
	    else getValue(xs,c)
	end
    end
	
	    
(*2.d*)
fun all_same_color(xs:card list)=
    case xs of
	[] => true
      | y::ys' => case ys' of
		      [] => true
		    | k::ks' => if  card_color(y)=card_color(k)
			       then
				   all_same_color(ys')
			       else
				   false;

				       
(*2.e*)

fun sum_cards(li:card list) =
    let fun helper(li:card list,sum:int)=
	    case li of
		[] => sum
	      | y::ys' => helper(ys',sum+(card_value(y)))
    in
	helper(li,0)
    end;


(*2.f score = fn : card list * int -> int
officiate = fn : card list * move list * int -> int*)

fun score(li:card list,goal:int ) =
    let val sum = sum_cards(li);val jud = all_same_color(li)
    in
	let val pre_score =(if sum>goal then 3*(sum-goal) else (goal-sum))
	in
	    case jud of
		false => pre_score
	      | true =>  pre_score div 2
	end
    end
; 

  
  (*2.g*)


fun officiate(li:card list,nx:move list,goal : int) =
    let
	fun helper(tmpList:card list,append:card) = tmpList@[append];
	fun runGame(lli:card list,nnx:move list,myList:card list) =
	    if sum_cards(myList)>goal then score(myList,goal)
	    else
	      case nnx of
		 [] =>  score(myList,goal)(*no operation*)
	       | y::ys' => case y of
			       Draw =>  (case lli of
					  [] => score(myList,goal) (*no card*)
					| z :: zs' => runGame(zs',ys',myList@[(z:card)]) (*continue*))
	                     | Discard(a,b) =>  runGame(lli,ys',remove_card(myList,(a,b),IllegalMove))
      in
	  runGame(li,nx,[])
      end
	  

第三题

Challenge Problems:
(a) Write score_challenge and officiate_challenge to be like their non-challenge counterparts except
each ace can have a value of 1 or 11 and score_challenge should always return the least (i.e., best)
possible score. (Note the game-ends-if-sum-exceeds-goal rule should apply only if there is no sum that
is less than or equal to the goal.) Hint: This is easier than you might think.
(b) Write careful_player, which takes a card-list and a goal and returns a move-list such that calling
officiate with the card-list, the goal, and the move-list has this behavior:
• The value of the held cards never exceeds the goal.
• A card is drawn whenever the goal is more than 10 greater than the value of the held cards. As a
detail, you should (attempt to) draw, even if no cards remain in the card-list.
• If a score of 0 is reached, there must be no more moves.
• If it is possible to reach a score of 0 by discarding a card followed by drawing a card, then this
must be done. Note careful_player will have to look ahead to the next card, which in many card
games is considered \cheating." Also note that the previous requirement takes precedence: There
must be no more moves after a score of 0 is reached even if there is another way to get back to 0.
Notes:
• There may be more than one result that meets the requirements above. The autograder should
work for any correct strategy | it checks that the result meets the requirements.
• This problem is not a continuation of problem 3(a). In this problem, all aces have a value of 11.
Coursera R编程的互评作业是一个很好的学习机会。通过这个作业,你将有机会编写R代码并与其他学员互相评估和交流。这个作业通常会在课程的后半部分出现,要求你完成一些相对复杂的编程任务。 在这个作业中,你将需要通过使用R语言来解决一些实际问题。这些问题可能涉及数据分析、数据可视化、统计模型等等。你会收到一份作业说明,并且需要根据要求编写相应的R代码。完成作业后,你需要将你的代码上传至Coursera平台上的作业提交系统。 完成代码编写后,你会被要求对一部分其他学员提交的代码进行评估。这意味着你会阅读他人的代码,并根据一些预定义的标准进行评分和反馈。这有助于你加深对R编程的理解,同时也能够向他人学习,看到其他人是如何解决同样的问题的。通过这个过程,你也能获取一些对你自己代码的反馈和建议。作为回报,你也需要对其他学员的作业进行评估,给出你对他们代码质量的评价。 此外,互评作业还带来了一种学习的动机,因为你知道你的作业会被他人评估。这鼓励你努力编写高质量的代码,并且对自己的作品有更高的标准。 总而言之,Coursera R编程的互评作业是一种非常有价值的学习机会。通过编写和评估他人的代码,你可以加深对R编程的理解,同时也能够从他人的经验中学习,并提高自己的编程水平。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值